Converting nested hash keys from CamelCase to snake_case in Ruby

后端 未结 6 488
一生所求
一生所求 2020-12-30 20:21

I\'m trying to build an API wrapper gem, and having issues with converting hash keys to a more Rubyish format from the JSON the API returns.

The JSON contains multip

6条回答
  •  长情又很酷
    2020-12-30 20:53

    If you use Rails:

    Example with hash: camelCase to snake_case:

    hash = { camelCase: 'value1', changeMe: 'value2' }
    
    hash.transform_keys { |key| key.to_s.underscore }
    # => { "camel_case" => "value1", "change_me" => "value2" }
    

    source: http://apidock.com/rails/v4.0.2/Hash/transform_keys

    For nested attributes use deep_transform_keys instead of transform_keys, example:

    hash = { camelCase: 'value1', changeMe: { hereToo: { andMe: 'thanks' } } }
    
    hash.deep_transform_keys { |key| key.to_s.underscore }
    # => {"camel_case"=>"value1", "change_me"=>{"here_too"=>{"and_me"=>"thanks"}}}
    

    source: http://apidock.com/rails/v4.2.7/Hash/deep_transform_keys

提交回复
热议问题