Ugly Ruby
Käännös: [ Google ]
Kategoriat: [ ATK ]
A few months ago, I started to use ruby for work. Twice I burnt my fingers on the following behaviour in Ruby:
def foo "bar" end puts "foo = #{foo.inspect}" if foo.nil? foo = "quux" puts "Not coming here" end puts "foo = #{foo.inspect}"The method foo returns the string
"bar"
, which is therefore not nil
. The
result any sane coder expects would be
foo = "bar" foo = "bar"What actually comes out when you run this snippet is
foo = "bar" foo = nil
I remember reading that in order to decide whether foo
is a call to the
foo method or the use of the local variable foo, Ruby checks the code
before for any assignment to foo. As it happens, the local variable foo
gets assigned inside the if clause, but the statement is never executed. My
guess is that Ruby then decides that the local variable foo is put to use
after the if clause, but is never actually assigned to, and therefore its
value is nil
. As it happens, the foo method still exists and returns
"bar"
, as expected, when called as foo()
.