Why does elsif work without passing it a condition to evaluate? It seems like this should break my code, yet it doesn't. Using elsif without a condition breaks in other languages, why not Ruby?
x = 4
if x > 5
puts "This is true"
elsif
puts "Not true - Why no condition?"
end
returns
Not true - Why no condition?
Adding an else branch at the end of the statement returns both the else and the elsif branches.
x = 4
if x > 5
puts "This is true"
elsif
puts "Not true - Why no condition?"
else
puts "and this?"
end
returns
Not true - Why no condition?
and this?
Thanks for helping me understand this quirk.
This is because your code actually interpreted as
if x > 5
puts "This is true"
elsif (puts "Not true - Why no condition?")
end
same also here
if x > 5
puts "This is true"
elsif (puts "Not true - Why no condition?")
else
puts "and this?"
end
puts
in your elsif
returns nil
, after printing "Not true - Why no condition?", which(nil
) is a falsy
value. Thus the else
is also triggered and "and this?"
also printed. Thus 2 outputs Not true - Why no condition?
and and this?
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With