Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if-elsif without conditions not branching correctly in Ruby

When I run the following code:

if  
  puts "A"  
elsif  
  puts "B"  
end  

I get the output:

A
B

Why does it not warn or raise any errors? And why does it execute both branches?

like image 620
angarciaba Avatar asked Nov 29 '22 08:11

angarciaba


2 Answers

In other words :

if # this is the condition :
    puts "A" # an expression which prints A and returns nil
# hence it's like "if false", try elsif ...
then
    puts 'passes in then'
elsif # this is another condition :
    puts "B" # puts prints B and returns nil
else # no condition satisfied, passes in else :
    puts 'in else'
end

Execution :

$ ruby -w t.rb 
A
B
in else
like image 22
BernardK Avatar answered Dec 08 '22 00:12

BernardK


an if-elsif without conditions

Here's where you're wrong. The puts are the conditions. There are no bodies in that snippet, only the conditions.

Here's your code, properly formatted.

if puts "A"  
elsif puts "B"  
end  

And why it executes both branches?

puts returns nil, a falsey value. That's why it tries both branches. If this code had an else, it'd be executed too.

like image 167
Sergio Tulentsev Avatar answered Dec 07 '22 22:12

Sergio Tulentsev