Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

概要

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

参考

QUANON
あんた、マジなんだな?
http://quanon.github.io/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした