LoginSignup
5
1

More than 5 years have passed since last update.

[rubyクイズ]&.とtry

Posted at

問題

1&.to_hoge #=> ?

:mouse:
:cow:
:tiger:
:rabbit:
:dragon_face:
:snake:
:horse:
:sheep:
:monkey_face:
:bird:
:dog:
:boar:
:mouse:
:cow:
:tiger:
:rabbit:
:dragon_face:
:snake:
:horse:
:sheep:
:monkey_face:
:bird:
:dog:
:boar:

答え

1&.to_hoge #=> NoMethodError: undefined method `to_hoge' for 1:Fixnum 

ちょっと解説

# 存在しないメソッドを呼ぶ場合、
# tryだとnilになるが、
# &.だとNoMethodErrorになる。
1.try(:to_hoge) #=> nil
1&.to_hoge #=> NoMethodError: undefined method `to_hoge' for 1:Fixnum 

#ちなみに、レシーバがnilだったら、どっちでもnilになる。
nil.try(:to_hoge) #=> nil
nil&.to_hoge #=> nil
5
1
2

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
5
1