In Ruby, why does a method invocation not be able to be treated as a unit when "do" and "end" is use

Posted by Jian Lin on Stack Overflow See other posts from Stack Overflow or by Jian Lin
Published on 2010-05-04T04:19:01Z Indexed on 2010/05/04 4:28 UTC
Read the original article Hit count: 239

Filed under:
|
|
|
|

The following question is related to

http://stackoverflow.com/questions/2127836/ruby-print-inject-do-syntax

The question is, can we insist on using DO and END and make it work with puts or p?

This works:

a = [1,2,3,4]

b = a.inject do |sum, x|
  sum + x
end
puts b   # prints out 10

so, is it correct to say, inject is a class method of the Array class, which takes a block of code, and then returns a number. If so, then it should be no different from calling a function and getting back a return value:

b = foo(3)
puts b

or

b = circle.getRadius()
puts b

In the above two cases, we can directly say

puts foo(3)
puts circle.getRadius()

so, there is no way to make it work directly by using the following 2 ways:

a = [1,2,3,4]

puts a.inject do |sum, x|
  sum + x
end

but it gives

ch01q2.rb:7:in `inject': no block given (LocalJumpError)
        from ch01q2.rb:4:in `each'
        from ch01q2.rb:4:in `inject'
        from ch01q2.rb:4

grouping the method call using ( ) doesn't work either:

a = [1,2,3,4]

puts (a.inject do |sum, x| 
        sum + x   
      end)

and this gives:

ch01q3.rb:4: syntax error, unexpected kDO_BLOCK, expecting ')'
puts (a.inject do |sum, x|
                 ^
ch01q3.rb:4: syntax error, unexpected '|', expecting '='
puts (a.inject do |sum, x|
                          ^
ch01q3.rb:6: syntax error, unexpected kEND, expecting $end
      end)
         ^

finally, the following version works:

a = [1,2,3,4]

puts a.inject { |sum, x|
    sum + x
  }

but why doesn't the grouping of the method invocation using ( ) work? What if a programmer insists that he uses do and end, can it be made to work directly with p or puts, without an extra temporary variable?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about error