将ruby哈希转换为另一个集合

时间:2017-02-21 20:32:25

标签: ruby

atts = {
    key1: "value1",
    key2: "value2"
}

然后应该产生以下内容:

custom_atts = {
    "key1" => {
    string_value: "value1",
    data_type: "String"
    },
    "key2" => {
    string_value: "value2",
    data_type: "String"
    }
}

所以我想创建一个将atts转换为custom_atts的函数。

def custom_atts(atts)

end

我可以像这样循环哈希值:

h.each do |key, value|
  puts key
  value.each do |k,v|
    puts k
    puts v
  end
end

但不确定如何在循环中创建带有哈希的哈希。

2 个答案:

答案 0 :(得分:1)

试试这个:

atts = {
    key1: "value1",
    key2: "value2"
}

def custom_atts(atts)

  Hash[ atts.keys.map { |key|
          [ key, {
              string_value: atts[key],
              data_type: "String" } ] } ]

end

puts custom_atts(atts).inspect

# {:key1=>
#  {:string_value=>"value1", 
#   :data_type=>"String"}, 
#  :key2=>{
#    :string_value=>"value2", 
#    :data_type=>"String"}}

如果您的新密钥应该是字符串而不是符号,请将key更改为地图内的key.to_s

答案 1 :(得分:0)

atts.each_with_object({}) { |(k,v),h| h[k.to_s] = { string_value: v, data_type: v.class } }
  #=> {"key1"=>{:string_value=>"value1", :data_type=>String},
  #    "key2"=>{:string_value=>"value2", :data_type=>String}}