beaglebets
beaglebets

Reputation: 315

Why does elsif work without a condition in 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.

Upvotes: 4

Views: 958

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118299

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

Upvotes: 7

falsetru
falsetru

Reputation: 369494

Because puts is used as a test expression. puts returns nil; control continues to next elsif/else.

x = 4

if x > 5
    puts "This is true"
elsif (puts "Not true - Why no condition?")
end

Upvotes: 2

C. K. Young
C. K. Young

Reputation: 223213

This is the same as:

if x > 5
  puts "This is true"
elsif puts "Not true - Why no condition?"
else
  puts "and this?"
end

The puts in your elsif returns nil, which is a false value, so the else is triggered.

Upvotes: 1

Related Questions