LoginSignup
51
30

More than 5 years have passed since last update.

||= とは?

Last updated at Posted at 2016-09-06

個人的なメモ

人のコードを拝見してるとたまに出てくる ||= は一体なんだろうかと。

irbで調べてみる。

変数にnilを与える。

irb(main):001:0> hoge = nil
=> nil

本題のメソッドを使って見る。
1回目に||= "hello,ruby"を入れると代入される。
2度目に||=を入れても"値が代入されない。"

irb(main):002:0> hoge ||= "hello, ruby"
=> "hello, ruby"
irb(main):003:0> hoge ||= "hello, hoge"
=> "hello, ruby"

もう一回試す。

irb(main):005:0> hoge = nil
=> nil
irb(main):006:0> hoge ||= "hello, hoge"
=> "hello, hoge"
irb(main):007:0> hoge ||= "hello, ruby"
=> "hello, hoge"
irb(main):008:0> 

わかったこと。

||= は変数に値がnilであれば、右辺の値(またはメソッド)を代入することができる
便利なやつ!

そして、irb先生便利。

51
30
1

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