by Locke · 16y ago · 0 comments
def ex1
a = 5
if a
puts "a: #{a}"
end
end
def ex2
if a = 5
puts "a: #{a}"
end
end
def ex3
puts "a: #{a}" if a = 5
end
If we start with the code in ex1 and decide to shorten it, ex2 is okay (although some people don't care for assignment in a conditional because it could be confused for a typo). But, ex3 will raise an exception that 'a' has not been defined.I've just internalized using the longer form when using assignment in a conditional.
$ irb
>> b
NameError: undefined local variable or method `b' for main:Object
from (irb):1
>> if defined? b
>> b = 5
>> end
=> nil
>> b
=> nil
>> defined? b
=> "local-variable"Take this for example:
ra:~$ irb
a = irb(main):001:0> a = b
NameError: undefined local variable or method `b' for main:Object
from (irb):1
irb(main):002:0> defined? a
=> "local-variable"
irb(main):003:0>
It just so happens that using statement modifiers in the way I tried using them brings this behavior to light.