8
7

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のkeyやvalueが数値の時はintegerに変換するメソッド

Last updated at Posted at 2014-10-07

JSON.parseとかしてきたときに、全部Stringになってしまって困ったので。

def convert h
  new_hash = Hash.new

  h.each do |k, v|
    if v.class == Hash
      v = convert v
    end

    if k.class == String and k.match(/^[0-9]*$/)
      k = k.to_i
    end

    if v.class == String and v.match(/^[0-9]*$/)
      v = v.to_i
    end

    new_hash[k] = v
  end

  new_hash
end

new_hash返すところで、new_hash.symbolize_keyとかすると数値以外のkeyがsymbolになって良い感じ

8
7
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
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?