0

y has been defined in if block, it will be nil. If that is removed, it gives an error: "undefined local variable or method `y' for main:Object".

if false
  y = 'hi'
end
puts y

Why can the variables in if-block initialize?

sawa
  • 165,429
  • 45
  • 277
  • 381
fcce
  • 1,034
  • 1
  • 12
  • 24
  • Where you are trying out your code? In irb it will never give such error if you simply define `y = 'hi'`. And here your if block is never executed as the condition is always false – Abhi May 05 '15 at 14:08
  • @Abhi It's not quite that simple, though; OP is asking how it's defined at *all*, not just why it's `nil`. – Dave Newton May 05 '15 at 14:16
  • Another duplicate: http://stackoverflow.com/questions/21180760/variable-in-else-condition-assumed-nil-value (itself marked as duplicate) – steenslag May 05 '15 at 14:18
  • @Dave I got the point after referring to the duplicate question. Thanks – Abhi May 05 '15 at 18:21

0 Answers0