shou2017.com
JP

Ruby Conditional Branches

Sun Mar 17, 2019
Sat Aug 10, 2024

Ruby differs from other languages in that:

  • Only false or nil are considered false.
  • Everything else is considered true.

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

プロを目指す人のためのRuby入門[改訂2版] 言語仕様からテスト駆動開発・デバッグ技法まで

See Also