使用变量Ruby调用Hash值

时间:2013-05-03 17:42:02

标签: ruby arrays variables hash

如何使用变量调用哈希值?

我有这样的哈希:data = {"5/3/2013 13:31:13"=>{:open=>65, :closed=>835}}

datasequences.each do |seq_title|
 sequence = Hash.new(0)
 sequence[:title] = seq_title
 sequence_data = Array.new(0)
 data.each do |key, value|
  puts value[#{seq_title.to_sym}]
  # More code...
 end
end

根据哈希(data),seq_title的值将为open,然后为closed

例如,如果我将代码更改为

datasequences.each do |seq_title|
 sequence = Hash.new(0)
 sequence[:title] = seq_title
 sequence_data = Array.new(0)
 data.each do |key, value|
  puts value[:open]
  # More code...
 end
end

在上面的代码中Ruby输出65,但是我想要值[var](不是硬编码的)所以它可以输出65并通过下一次迭代835.

3 个答案:

答案 0 :(得分:1)

由于该值本身就是一个哈希值,因此您可以打印键和值,如下所示:

data.each do |key, value|
  value.each do |k,v|
    puts "#{k}: #{v}"
  end
  # More code...
end

答案 1 :(得分:1)

您只需要使用变量指定密钥:

% irb
irb> data = {  "5/3/2013 13:31:13"=>{:open=>65, :closed=>835}, "5/4/2013 14:41:14"=>{:open=>56, :closed=>538} }
# => {"5/3/2013 13:31:13"=>{:open=>65, :closed=>835}, "5/4/2013 14:41:14"=>{:open=>56, :closed=>538}} 
irb> datasequences = [ :open, :closed ]
# => [:open, :closed] 
irb> datasequences.each do |seq_title|
irb|   puts "seq_title is #{seq_title.inspect}"
irb|   data.each do |key, value|
irb|     puts "\t#{value[seq_title]} at #{key}"
irb|   end
irb| end
seq_title is :open
  65 at 5/3/2013 13:31:13
  56 at 5/4/2013 14:41:14
seq_title is :closed
  835 at 5/3/2013 13:31:13
  538 at 5/4/2013 14:41:14
# => [:open, :closed] 

答案 2 :(得分:0)

您需要使用Hash#values_at,如下所示:

data = {"5/1/2013 10:42:40" => {"open" => 10,"closed" => 345},"5/2/2013 10:42:40" => {"open" => -1,"closed" => 700}}
datasequences = [ :open, :closed ]

data.each do |k,v|
  p v.values_at(*datasequences.map(&:to_s))
end

输出:

[10, 345]
[-1, 700]