I'm learning ruby and can't figure out what's the problem here.
formatter = "%s %s %s %s"
puts formatter = % [1, 2, 3, 4]
Result:
ex8.rb:3: syntax error, unexpected tINTEGER, expecting $end
puts formatter = % [1, 2, 3, 4]
^
You either a) Don't need that = sign:
formatter = "%s %s %s %s"
puts formatter % [1, 2, 3, 4]
or b) need to assign the result to formatter differently:
formatter = "%s %s %s %s"
puts formatter = formatter % [1, 2, 3, 4]
or
formatter = "%s %s %s %s"
formatter = formatter % [1, 2, 3, 4]
puts formatter
The former answer for b will assign the result to formatter and then output the result of that assignment, which will be the right-hand side. I'd recommend the latter (and you could of course condense the top two lines into a single line) just because it's clearer.
Edit:
Also, if you check the code in Learn Ruby the Hard Way, they're not reassigning anything to formatter. The point is that you can supply any four-item array via formatter % and it will produce the text content of those four items. I see it's just dipping into Ruby methods (and you may be unfamiliar with printf), but the following are equivalent:
puts formatter % [1, 2, 3, 4]
puts formatter.%([1, 2, 3, 4])
# And the very retro
puts sprintf(formatter, 1, 2, 3, 4)
In other words, while there are a few nuances for operators -- just some sugar that you can actually use things like %= to assign the result and you don't need the . separating the object and its method -- these are just methods. You can look up % in Ruby's documentation like any other method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With