Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby lazy if statement with no operator

Is it possible to do this in ruby?

variablename = true
if variablename
   puts "yes!"
end

Instead of this

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

Edit: also considering having:

variablename = 0 #which caused my problem

I can't get that to work. Is such a style of saying if possible? I'm learning ruby now, and it is possible in PHP but im not sure how to do it right in ruby

like image 390
Tarang Avatar asked Sep 04 '25 16:09

Tarang


2 Answers

sure, it's possible

everything except nil and false is treated as true in ruby. Meaning:

var = 0
if var
  # true!
end

var = ''
if var
  # true!
end

var = nil
if var
  # false
end
like image 118
Vlad Khomich Avatar answered Sep 07 '25 17:09

Vlad Khomich


xdazz and Vlad are correct with their answers, so you would 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
like image 36
Thomas Nadin Avatar answered Sep 07 '25 17:09

Thomas Nadin