Ruby differs from other languages in that:
false
or nil
are considered false.This Ruby characteristic is useful in situations like when you want to write code that returns data if it exists, or returns nil if it doesn’t. If written normally, it would look like this:
data = find_data
if data != nil
'Data exists'
else
'Data does not exist'
end
In Ruby, you can write it like this:
data = find_data
if data
'Data exists'
else
'Data does not exist'
end
Additional note:
!=
compares strings.
When comparing strings in Ruby, use ==
to check if strings are the same, and use !=
to check if they are different.
'ruby' == 'ruby' #=> true
'ruby' == 'Ruby' #=> false
'ruby' != 'java' #=> true
'ruby' != 'ruby' #=> false