1)
!
, negations - it changes every object except nil
and false
to false (other objects into true
)
2) name?
should return false(false
and nil
) or true value (everything else). In most cases it will be true
or false
objects.
Methods with with ?
at the end suggest that they are predicates. In your example nil?
checks if object is nil. In other language you may find something like this: is_nil
.
Other examples:
[].empty? # true
3.zero? # false
0.zero? # true
3) The colon in your example is part of a ternary if.
'cond' ? 'true value' : 'false value'
is similar to:
if 'cond'
'true value'
else
'false value'
end
One difference between ?:
and if else
is precedence:
def foo a
a # just return a
end
foo 2 ? 3 : 4
# => 3
foo if 2 then 3 else 4 end
# error
In the last example Ruby wanted to run function1 if condition
but it found function if condition #some garbage
, so Ruby raised an error.