LoginSignup
4
0

More than 1 year has passed since last update.

【Ruby】Safe Navigation Operator &.

Last updated at Posted at 2023-01-19

Safe Navigation Operator &.

&.という演算子を使用してメソッドを呼び出すと、レシーバーがnilだった場合でもエラーが発生しなくなります。

class Hoge
  def hoge 
    "hoge"
  end
end
> hoge = Hoge.new
=> #<Hoge:0x000000010e850c78>
> hoge.hoge
=> "hoge"

> fuga = nil
=> nil
> fuga.hoge
NoMethodError (undefined method 'hoge' for nil:NilClass)

irb(main):010:0> fuga&.hoge
=> nil

if文や条件分岐の書き換え

  • if
hoge = if fuga
  fuga.hoge
else
  nil
end

=> nil
  • 三項演算子
hoge = fuga ? fuga.hoge : nil

=> nil
  • Safe Navigation Operator
hoge = fuga&.hoge

=> nil

参考

4
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
4
0