23
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby2.3のSafe Navigation Operator

Last updated at Posted at 2016-04-18

Ruby2.3の新機能、Safe Navigation Operator
うっかりはまったのでメモ

メソッド呼び出しの.の前に&をつけておくと、レシーバーがnilのときにNoMethodErrorを投げずにnilを返してくれる機能です。

str = nil
str&.upcase  #=>nil

ただしこの機能は&と.をセットで書かないと使えないようで、例えばこういう書き方はできません。

#論理演算子のNilclass#&が呼ばれる
ary = nil
p ary&[0]  #=>false

#Array#&(配列の積集合)
ary = [1, 2, 3]
p ary&[0]  #=>[]

#これならOK
p ary&.[](0)  #=>1
#それならこう書いた方がいい気がする
p ary&.at(0)  #=>1

#ちなみにこういうのはSyntaxError
num = nil
#num& == 0
#num& * 2

考えてみれば、論理演算子やArray#&のようなメソッドと区別するためにこのような仕様なのは当たり前ですね…

23
28
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
23
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?