Thursday, March 31, 2011

Using print instead of sprintf with %s and % and multiple string substitution arguments

In the following ruby code, the output becomes: "x y"

x = "x %s"
y = "y"
z = "z"
print x % y %z

The %z is ignored.

I want the output to be "x y z".

To understand the possibilities and limitations of the syntax of Ruby, I want to use only the print command and the %s and % flags. I know how to do this using sprintf but I want to know if there's a way to do it with just the 'print' command.

So I tried adding a second %s to the definition of the variable 'x':

x = "x %s %s"
y = "y"
z = "z"
print x % y %z

But I got this error:

in `%': too few arguments (ArgumentError)

With sprintf you could do this:

x = "x %s %s"
y = "y"
z = "z"
print (sprintf(x, y, z))

The output would be what I wanted:

x y z

But that's just too easy.

Is there a way to do this with just 'print' (not sprintf) and without using #{} or combining y and z into an array as [y,z]?

From stackoverflow
  • I don't actually understand what you want to do, but:

    irb(main):001:0> x = "x %s"
    => "x %s"
    irb(main):002:0> y = "y %s"
    => "y %s"
    irb(main):003:0> z = "z"
    => "z"
    irb(main):004:0> print x % y % z
    x y z=> nil
    

    and:

    irb(main):006:0> x = "x %s %s"
    => "x %s %s"
    irb(main):007:0> y = "y"
    => "y"
    irb(main):008:0> z = "z"
    => "z"
    irb(main):009:0> x % [y,z]
    => "x y z"
    
  • Use print "x #{y} #{z}".

    I could not find much documentation easily with Google... however here are some pages where this usage is demonstrated:

    http://www.rubycentral.com/pickaxe/tut_expressions.html

    http://linuxgazette.net/issue81/ramankutty.html

    http://search.cpan.org/~neilw/Inline-Ruby-0.02/lib/Inline/Ruby.pod

    jheriko : i don't know. i think i better question is "why avoid using the #{} notation?".
  • Might this be what you want?:

    irb(main):001:0> x = "x %s %s"
    => "x %s %s"
    irb(main):002:0> y = "y"
    => "y"
    irb(main):003:0> z = "z"
    => "z"
    irb(main):004:0> print x % [y,z]
    x y z=> nil
    
  • The consensus seems to be that you can't avoid using the #{} substitution syntax. And the % notation only seems to work if you use an array [y,z] to combine the two variables into a single unit.

    What I really wanted, though was some way to do this:

    print x % y, z

    without combining the y and z variables into one.

    Perhaps this is not possible and you either have to:

    1. Use #{} substitution
    2. Combine y and z into an array and then call print x % [y,z]
    3. Use sprintf like this: print (sprintf(x, y, z))

    and define x as:

    x = "x %s %s"

0 comments:

Post a Comment