rubymri

Why can't I print the result of reduce/inject directly


Found an interesting quirk in the ruby interpreter - at least in MRI 2.4.2.

As far as I can tell, each of the below code snippets should print '123'. If I try to print the result of reduce directly, I get NoMethodError: undefined method '' for 1:Integer (or whatever type the array contains) But if I first save the result and then print it, it works fine..

So, this code is broken:

puts [1,2,3].reduce('') do |memo, num|
  memo + num.to_s
end

And this code works:

temp = [1,2,3].reduce('') do |memo, num|
  memo + num.to_s
end
puts temp

These should work exactly the same, right? Should this be filed as a bug? Am I just missing something fundamental here?

I'd think it should at least show which method is trying to be called. Can't find anything in google about an undefined method without a method name...


Solution

  • You need parenthesis on the puts call. This works:

    puts([1,2,3].reduce('') do |memo, num|
      memo + num.to_s
    end)
    

    Normally you can avoid parenthesis, but sometimes the parser will find ambiguities and will just raise an error, like in your first case.