Ruby lazy if statement without statement

Can this be done in ruby?

variablename = true
if variablename
   puts "yes!"
end

      

Instead of this

variablename = true
if variablename == true
   puts "yes!"
end

      

Edit: also given the presence of:

variablename = 0 #which caused my problem

      

I cannot get this to work. Is this a style of saying, if possible? I am learning ruby ​​now and it is possible in PHP but I am not sure how to do it in ruby

+3


source to share


3 answers


sure, maybe

everything except nil

and false

is treated as true in ruby. Value:



var = 0
if var
  # true!
end

var = ''
if var
  # true!
end

var = nil
if var
  # false
end

      

+8


source


xdazz and Vlad are correct with the answers, so you will need to catch 0

separately:



variable = false if variable.zero?  # if you need 0 to be false
puts "yes!" if variable             # now nil, false & 0 will be considered false

      

+3


source


It is possible at all. In ruby ​​only nil

and false

is considered false, any other value is true.

+1


source







All Articles