If-elsif without conditions not forking correctly in Ruby

When I run the following code:

if  
  puts "A"  
elsif  
  puts "B"  
end  

I get the output:

A
B

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

+4
source share
2 answers

if-elsif no conditions

Here where you are mistaken. puts are conditions. There are no bodies in this fragment, only conditions.

Here is your code, correctly formatted.

if puts "A"  
elsif puts "B"  
end  

And why does it execute both branches?

putsreturns nil, false. That is why he is trying both branches. If this code had else, it would also be executed.

+19
source

In other words:

if # this is the condition :
    puts "A" # an expression which prints A and returns nil
# hence it 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
+2
source

Source: https://habr.com/ru/post/1688083/


All Articles