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
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
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
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