Converting nested hash keys from CamelCase to snake_case in Ruby

后端 未结 6 464
一生所求
一生所求 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

    Use deep_transform_keys for recursive conversion.

    transform_keys only convert it in high level

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

    deep_transform_keys will go deeper and transform all nested hashes as well.

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

提交回复
热议问题