Ambiguity resolving: "block " vs "method [5]"

Just curious how Ruby resolves the ambiguity when calling a method with
a list,
and invoking the [] operator on a block:

def foo(i)
p i
end

bar = lambda { |i| p i }

foo [1]
bar [1]

I’m assuming it’s doing a little compile time checking, or lazily
converting
the call to the correct type at runtime?

Mike

On Mon, Dec 6, 2010 at 1:21 AM, Mike A.
[email protected] wrote:

bar [1]

I’m assuming it’s doing a little compile time checking, or lazily converting
the call to the correct type at runtime?

One important differentiation is local variable or not. If it is a
local variable, Ruby knows that there are no arguments and the
following must be method call on the object held in the variable. If
it is not a local variable a space indicates arguments while a missing
space before “[” indicates that we have a call of method #[]. Try
this:

def foo(i) printf(“Meth %p\n”, i) end
bar = lambda {|i| printf(“Block %p\n”, i)}
def baz; lambda {|i| printf(“BlockMeth %p\n”, i)} end
foo [1]
bar [2]
#baz [3]
#foo[4]
bar[5]
baz[6]

Commented lines fail:

3: wrong number of arguments (1 for 0) (ArgumentError)
4: wrong number of arguments (0 for 1) (ArgumentError)

Kind regards

robert