将哈希键转换为驼峰式

问题描述 投票:0回答:2

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
2个回答
3
投票

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
返回符号。


1
投票

对于红宝石你可以做这样的事情

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 中不可用。

© www.soinside.com 2019 - 2024. All rights reserved.