October 6, 2006

Ruby quirk

I worry when my computer languages exhibit the following kind of behaviour


# example 1 does not work
a = [2,3,4,5]
puts a.max {|a,b| a <=> b}
puts a.max {|a,b| a <=> b} #runtime error - a is now an integer

This example fails! The block variable, far from being a local parameter in the block, actually exists in the same scope as the array a. to evaluate the block the procedure assigns to the variable a destorying the array.

# example 2 works
def max(a)
a.max {|a,b| a <=> b}
end

a = [2,3,4,5]
puts(max(a))
puts(max(a))



This works. Function call parameters are proper variables existing in the scope of the function - not the caller. The a inside the function is still destroyed - but is not reused.

Bug or quirk? I think bug.

Posted by Claus at October 6, 2006 12:45 PM
Comments
Post a comment