3

Are there any kind of shortcut for code like this?

def test
  obj = get_from_somewhere()
  if obj
    true
  else
    false
  end
end

In Python, I can do like this:

return True if obj else False
toro2k
  • 19,020
  • 7
  • 64
  • 71
kemmotar
  • 199
  • 2
  • 15

3 Answers3

10

A common Ruby idiom to achieve this is:

def test
  !!get_from_somewhere
end

The double bang turns an object into its "boolean equivalent":

object = 'foo'
!object
# => false
!!object
# => true

Pay attention that in Ruby, unlike Python, just false and nil evaluates to false in boolean context, for example:

!!0
# => true
Community
  • 1
  • 1
toro2k
  • 19,020
  • 7
  • 64
  • 71
  • 1
    Just don't forget to add a link to [What does !! mean in ruby?](http://stackoverflow.com/questions/524658/what-does-mean-in-ruby) when using this outside your personal projects ;) – Stefan Sep 20 '13 at 14:02
7

The ! is the not/negate operator. It turns the object into a Boolean variable that is the negative of its value. So, if test = 1, then !test is false because test is true. (Any value that is not false or nil is true.)

Using !! is not a specific operator, it is just ! twice. So, if a value is neither false nor nil, then !! returns true.

That being said, a more obvious way of writing the expression nearly equivalent to PHP is the ternary operator:

def test
  obj = get_from_somewhere()
  obj ? true : false  # Returns true as long as obj is neither false nor nil.
end

Or, even more simply if you don't need the obj variable:

def test
  get_from_somewhere() ? true : false  # Returns true as long as get_from_somewhere() is neither false nor nil.
end
Richard_G
  • 4,700
  • 3
  • 42
  • 78
0

How about this:

obj ? true : false
Stobbej
  • 1,080
  • 9
  • 17