hash = {test_user: '1', user_details: {first_name: "Test"}}
output = {testUser: '1', userDetails: {firstName: "Test"}}
节目:
new_hash = {}
if hash.values.map{|x| x.class}.include?(Hash)
hash.each do |k,v|
if v.class == Hash
new_hash[k.to_s.upcase] = hash.transform_keys{ |key| key.to_s.upcase }
else
new_hash[k.to_s.upcase] = v
end
end
puts new_hash
end
它给出这样的输出:
{"TEST_USER"=>"1", "USER_DETAILS"=>{"TEST_USER"=>"1", "USER_DETAILS"=>{:first_name=>"Test"}}}
有人可以帮助我获得正确的输出吗?
Ruby on Rails 有一个内置方法可以转换深度嵌套哈希中的键。
Hash#deep_transform_keys
与 String#camelize
结合使用,如下所示:
hash = { test_user: '1', user_details: { first_name: "Test" }}
hash.deep_transform_keys { |key| key.to_s.camelize(:lower).to_sym }
#=> { :testUser => "1", :userDetails => { :firstName=>"Test" }}
请注意,在调用
to_s
之前,您需要使用 camelize
将符号化键转换为字符串,并使用 to_sym
返回符号。
对于红宝石你可以做这样的事情
def camelize_hash(hash)
new_hash = {}
hash.each do |key, value|
if value.is_a?(Hash)
new_hash[camelize_str(key).to_sym] = camelize_hash(value)
else
new_hash[camelize_str(key).to_sym] = value
end
end
new_hash
end
def camelize_str(str)
str.to_s.gsub(/_([a-z0-9])/) { Regexp.last_match[1].upcase }
end
hash = {test_user: '1', user_details: {first_name: "Test"}}
new_hash = camelize_hash(hash)
更新:
camelize
方法适用于 Rails,在普通 Ruby 中不可用。