Home > Software design >  (ruby) If a conditional variable is nil in an if-else block statement, what will the program print i
(ruby) If a conditional variable is nil in an if-else block statement, what will the program print i

Time:11-28

In ruby, let's suppose there is a variable foo, and we assign foo = nil, and then we have this code:

if foo
  puts "foo is true"
else
  puts "foo is false"
end

what will this above program print exactly?

CodePudding user response:

Usually, Ruby developers do not care that much if a variable or condition is exactly true or false. Instead Ruby has the concept of truthy and falsey values.

false and nil are falsey, everything else is truthy.

In your example

if foo
  puts "foo is true"
else
  puts "foo is false"
end

the output would be "foo is false" because nil is falsey and therefore the else block is evaluated.

When running the example in the console then nil would be returned at the end, because nil is returned by the puts method (see docs) and the Ruby console always returns the return value of the last method call.

CodePudding user response:

The answer is that code above will print "foo is false" and also output nil. If someone knows why please comment on this answer or post a new answer to the above question.

So,

if foo
  puts "foo is true"
else
  puts "foo is false"
end

will print:
foo is false
=> nil
if you are using ruby console

  •  Tags:  
  • ruby
  • Related