简体   繁体   English

Ruby:如何遍历哈希项数组?

[英]Ruby: how to iterate over an array of hash items?

irb> pp config
[{"file"=>"/var/tmp"},
 {"size"=>"1024"},
 {"modified"=>"03/28/2012"}]
=> nil

In the code, 在代码中

config.each do |d|
  # then how to break d into (k, v)???
end
config.each do |items|
  items.each do |key, value|
    # e.g. key="file", value="/var/tmp", etc.
  end
end

Just do 做就是了

config.each do |hash|
  (k,v),_ = *hash
end

Inspired by @Arup's answer , here's a solution that doesn't require a extra, unused variable in the parallel assignment: 受到@Arup的答案的启发,以下解决方案在并行分配中不需要额外的未使用变量:

config.each do |hash|
  key, value = hash.to_a[0]
end

to_a converts the hash into the same kind of array that you would get by using splat *hash , but you can actually index the first element of the array (ie the first key/value pair) with [0] this way, while trying to do so with splat (*hash) generates a syntax error (at least in Ruby version 2.1.1): to_a将散列转换为与使用splat *hash所获得的数组相同的数组,但是实际上您可以通过[0]这样用[0]索引数组的第一个元素(即第一个键/值对),同时尝试使用splat (*hash)这样做会产生语法错误(至少在Ruby版本2.1.1中):

>> k,v = (*hash)[0]
SyntaxError: (irb):4: syntax error, unexpected ')', expecting '='
k,v = (*x)[0]
          ^
        from c:/RailsInstaller/Ruby1.9.3/bin/irb:12:in `<main>'
>>

Of course, depending on what you're going to do with the key and value variables, it might make your code shorter and more readable to use one of these standard block constructs: 当然,根据要使用keyvalue变量的不同,使用以下标准块结构之一可能会使代码更短,更易读:

config.each do |hash|
  hash.each { |key,value| puts "#{key}: #{value}" }
end

# or

config.each do |hash|
  hash.each do |key,value|
    puts "#{key}: #{value}"
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM