0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Ruby】よくみるイディオム(nillガード、!!を使った真偽値の型変換)

Posted at

はじめに

記事でよくみるRuby定番の書き方を身に付けたい。という想いからよくみる慣用的な表現をまとめました。

|| =(nilガード)

「変数にnil以外の方を入れておきたい」という目的でつかわれる。

a = nil
a ||= 10  
a #=> 10

a = 5
a ||= 10  
a #=> 5

なぜ、aがnilの場合だけ10が代入されるのか。
実は、上の式は以下と同じ。

a = nil
a || a = 10
a #=> 10

a = 5
a || a = 10  
a #=> 5

論理演算子||は、左側が真なら右側を評価せずに終了するという性質を持っている。
anil(偽)ならa = 10が実行され、aがすでに値を持っていれば、そのままaを使う。

!!()

Rubyはnil又はfalseであれば偽、それ以外は全て真。

!!を使うことで、値を確実に true または false に変換することができる。
1回目の!で値をtruefalseで変換し、2回目の!で純粋な真偽値を返す。

!!nil     # => false
!!false   # => false
!!0       # => true
!!"text"  # => true

真偽値が欲しいときに、他の型の値を受け取る可能性がある場合は!!を使うことで明確な真偽値を返すことができる。

def logged_in?
  !!session[:user_id]
end

まとめ

  • ||= は「nilだったら代入する」ための便利な書き方。初期化やキャッシュに使える。
  • !! は「真偽値として扱いたい値を明確にtrue/falseに変換」できる。
  • どちらもRubyらしい柔らかい構文で、短く・安全なコードを書くための基本的なイディオム。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?