Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected tINTEGER, expecting $end

Tags:

ruby

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] 
                        ^
like image 834
deadghost Avatar asked Jul 12 '26 05:07

deadghost


1 Answers

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.

like image 155
brymck Avatar answered Jul 14 '26 00:07

brymck