4

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

3
  • 3
    Saying something like "I can't get it to work" doesn't help anyone diagnose what you're doing wrong; as shown it works fine for me. Commented Mar 18, 2012 at 10:32
  • I had it my variablename = 0 and couldn't figure out why 'it wouldn't work'. From below I can see its that ruby considers 0 as true Commented Mar 18, 2012 at 10:41
  • I can see I set true there but here im asking if this coding style is possible. I appologize Commented Mar 18, 2012 at 10:42

3 Answers 3

10

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
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting. that '0' is what confused me
It not treated as true but just truthy, so only in statements that query for trutyiness (e.g. if or case) it's equivalent. But if you compare truthy values with trueyou will still get non-equality.
3

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

2 Comments

A more "ruby" way would be variable = false if variable.zero?. Having said that, one should understand the limitations(?) of the language and do not use zero is such cases.
Thank you, updated my answer to reflect that. And you're right about design choices made in ruby, but if this was a business logic problem that need acting upon rather than a programming choice, it is appropriate.
1

It's possible at all. In ruby, only nil and false is considered as false, any other value is true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.