LoginSignup
27
19

More than 5 years have passed since last update.

fetchと[]の違いを、try hash で知りました。

Posted at
a = {name: 'taro'}

a.try(:[], :name)

という書き方を教わりました。

a.try(:fetch, :name)

でもいけます。けど。

pry(main)> a.try(:[], :email)
# => nil

pry(main)> a.try(:fetch, :email)
# KeyError: key not found: :email from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-4.1.8/lib/active_support/core_ext/object/try.rb:45:in `fetch'

#となりますので、fetchの場合は、以下のようにします。

pry(main)> a.try(:fetch, :email, nil)
=> nil

そもそも、[]がメソッドということですので、

a[:name]
# => "taro"

a.[] :name
# => "taro"

という風にかけるんですね。それで、fetchと[]が、keyの有無でちょっとだけ挙動が変わるということでございますね。

とにかく、勉強になりました。ありがとうございます。

27
19
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
27
19