哈希到阵列转换

时间:2015-04-26 08:24:09

标签: ruby arrays hash

以下响应由外部API返回,并分配给ret_val

{:val1=>"add", :val2=>"delete", :val3=>"update"}
{:val1=>"add_name", :val2=>"delete_name", :val3=>"update_name"}
{:val1=>"add_city", :val2=>"delete_city", :val3=>"city"}

我想将ret_val转换为数组,以便通过提供val1来提取分配给val2val3val1的值, val2val3。所以我基本上希望看到所有逗号分隔对的键值和值对。 预期产出:

val1 : add
val2 : delete
val3:update

直到API返回的最后一行。  请建议。 注意:API将始终仅使用重复键以上述格式返回响应。

3 个答案:

答案 0 :(得分:1)

更新的答案:如果您只想在JSON中重现相同的结构,可以使用Ruby JSON module

require 'json'

ret_val = [
    { :val1 => "add", :val2 => "delete", :val3 => "update" },
    { :val1 => "add_name", :val2 => "delete_name", :val3 => "update_name" },
    { :val1 => "add_city", :val2 => "delete_city", :val3 => "update_city" }
]

puts ret_val.to_json
# => [{"val1":"add","val2":"delete","val3":"update"},{"val1":"add_name","val2":"delete_name","val3":"update_name"},{"val1":"add_city","val2":"delete_city","val3":"update_city"}]

如果需要重新构造结构,则需要迭代响应数组中的哈希值,例如使用Array#each。您可以将块与函数关联,并为阵列中的每个条目执行块。为了说明,让我们看一下my_array = ["one", "two", "three"]

my_array = ["one", "two", "three"]
my_array.each do |e|
  # e is the current entry
  puts "The current entry is '#{e}'"
end

输出为

The current entry is 'one'
The current entry is 'two'
The current entry is 'three'

以同样的方式,你可以迭代你从API获得的数组中的哈希值,并像你想要的那样处理每个哈希值

ret_val = ... # same as above
ret_val.each do |hash|
  # do whatever you need to do with 'hash'
end

您正在寻找的内容可能是Hash#values

my_hash = {:val1=>"add", :val2=>"delete", :val3=>"update"}
my_hash.values # => ["add", "delete", "update"]

答案 1 :(得分:1)

下面的代码片段会给你想要的结果:

#ret_val=calling API
ret_val.each { |x|  
x.each { |val| 
puts "#{val[0]} :#{val[1]}"
}
}

答案 2 :(得分:0)

API返回的是哈希。您可以通过其密钥访问哈希值。

ret_val = func()

ret_val是一个哈希对象。要访问其值

a = Array.new()
ret_val.each { |key,value| a << value }