VOOZH about

URL: https://qiita.com/color_box/items/01dac020f441b4789d99

⇱ シンボルハッシュを文字列ハッシュに変換するワンライナー #Ruby - Qiita


👁 Image
2

Go to list of users who liked

1

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

More than 5 years have passed since last update.

@color_boxin👁 Image
株式会社永和システムマネジメント

シンボルハッシュを文字列ハッシュに変換するワンライナー

2
Last updated at Posted at 2015-11-30

railsで、コントローラに渡されたパラメータを、キーワード引数としてメソッドにそのまま渡そうとするとエラーになる。
ハッシュがのキーシンボルであるため、これらのキーを文字列に変換してやる必要がある。

hash_change
my_hash = my_hash.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}

参考
http://stackoverflow.com/questions/800122/best-way-to-convert-strings-to-symbols-in-hash

追記
railsであればハッシュに対してstringify_keys メソッドを使用するほうが簡単である。

2

Go to list of users who liked

1
3

Go to list of comments

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
2

Go to list of users who liked

1