Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does elsif work without a condition in Ruby?

Tags:

ruby

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.

like image 683
beaglebets Avatar asked Dec 26 '22 13:12

beaglebets


1 Answers

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?.

like image 65
Arup Rakshit Avatar answered Jan 12 '23 06:01

Arup Rakshit