10
4

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.

Ruby 2.3 のぼっち演算子を使うときにやりがちなミス

Last updated at Posted at 2016-12-15

Ruby 2.3 で導入された &. 演算子(safe navigation operator = ぼっち演算子)を使うときに、個人的に何度かやらかした間違いを書いておきます。

# 誤
object&.foo.bar
# 正
object&.foo&.bar

間違い例の場合、 NoMethodError が発生します。

irb(main):001:0> nil&.foo&.bar
=> nil
irb(main):002:0> nil&.foo.bar
NoMethodError: undefined method `bar' for nil:NilClass
        from (irb):2
        from /home/key-amb/.rbenv/versions/2.3.1/bin/irb:11:in `<main>'

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?