7 ms·
Yes, they are different. For example: def ex1 a = 5 if a puts "a: #{a}" end end def ex2 if a = 5 puts "a
by Locke 17y ago
Yes, they are different. For example:
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.
- chief 17y agoI think the article is wrong. His rewrite on line 06. should use if instead of unless. $ 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"
- angilly 17y agoNo, it's using unless like I intended. But your example also demonstrates the weird behavior. As a few people have pointed out here and over in the post comments, the issue at hand isn't so much about statement modifiers as it is about how Ruby 'defines' local variables. 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.