295
199

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.

Hash から文字列でもシンボルでも値を取り出す

Last updated at Posted at 2014-11-14

概要

Ruby の Hash は key が文字列かシンボルかどうかを区別します。

hash = { yuno: 'ゆの', miyako: '宮子' }
hash[:yuno]  #=> "ゆの"
hash['yuno'] #=> nil

hash = { 'sae' => '沙英', 'hiro' => 'ヒロ' }
hash[:sae]  #=> nil
hash['sae'] #=> "沙英"

きっちりしてて結構なんだけど、
key が文字列かシンボルか意識しなくても value を取り出せるとありがたい場合もありますよね。

そういえば、Rails 4 の Controller の params って文字列でもシンボルでも value を取り出せますよね。
あれの型は実は Hash ではなくて Hash のサブクラスである ActiveSupport::HashWithIndifferentAccess なんです!
(正確には、さらにそのサブクラスである ActionController::Parameters です。)

Hash を HashWithIndifferentAccess に変えてその恩恵を受けるには Hash#with_indifferent_access というインスタンスメソッドを利用します。

require 'active_support'
require 'active_support/core_ext'

sugoi_hash = { yuno: 'ゆの', miyako: '宮子' }.with_indifferent_access
sugoi_hash[:yuno]  #=> "ゆの"
sugoi_hash['yuno'] #=> "ゆの"

やったね宮ちゃん! (ドヤァ

1NFb2.jpg

参考

295
199
10

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
295
199

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?