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