我有以下哈希值:
{
"01/01"=>{:a=>0, :b=>2},
"01/05"=>{:a=>1, :b=>0},
"31/08"=>{:a=>26, :b=>32},
"01/09"=>{:a=>2, :b=>9},
"02/09"=>{:a=>0, :b=>3},
"04/09"=>{:a=>0, :b=>4},
"06/09"=>{:a=>0, :b=>26},
"07/09"=>{:a=>0, :b=>2},
"06/10"=>{:a=>0, :b=>1},
"07/11"=>{:a=>0, :b=>1}
}
该哈希有10个条目,但我只需要显示7个即可。 我怎样才能只获得7个条目来使用这些值?
谢谢。
答案 0 :(得分:1)
前7个元素
您可以在转换为数组的哈希上使用Array#slice
,然后再转换回哈希。这是一个示例:
x = {
"01/01"=>{:a=>0, :b=>2},
"01/05"=>{:a=>1, :b=>0},
"31/08"=>{:a=>26, :b=>32},
"01/09"=>{:a=>2, :b=>9},
"02/09"=>{:a=>0, :b=>3},
"04/09"=>{:a=>0, :b=>4},
"06/09"=>{:a=>0, :b=>26},
"07/09"=>{:a=>0, :b=>2},
"06/10"=>{:a=>0, :b=>1},
"07/11"=>{:a=>0, :b=>1}
}
y = x.to_a.slice(0,7).to_h
然后y
是
{
"01/01"=>{:a=>0, :b=>2},
"01/05"=>{:a=>1, :b=>0},
"31/08"=>{:a=>26, :b=>32},
"01/09"=>{:a=>2, :b=>9},
"02/09"=>{:a=>0, :b=>3},
"04/09"=>{:a=>0, :b=>4},
"06/09"=>{:a=>0, :b=>26}
}
哈希还具有切片方法(至少在2.5.1中),但是需要提供从哈希中进行切片的键。如果您事先知道按键,则可以:
y = x.slice("01/01", "01/05", "31/08", "01/09", "02/09", "04/09", "06/09")
对于y
,结果相同。
Hash#slice
文档:https://ruby-doc.org/core-2.5.1/Hash.html#method-i-slice
最后7个元素
您可以在转换为数组的哈希上使用Array#last
,然后再转换回哈希。这是一个示例:
x = {
"01/01"=>{:a=>0, :b=>2},
"01/05"=>{:a=>1, :b=>0},
"31/08"=>{:a=>26, :b=>32},
"01/09"=>{:a=>2, :b=>9},
"02/09"=>{:a=>0, :b=>3},
"04/09"=>{:a=>0, :b=>4},
"06/09"=>{:a=>0, :b=>26},
"07/09"=>{:a=>0, :b=>2},
"06/10"=>{:a=>0, :b=>1},
"07/11"=>{:a=>0, :b=>1}
}
y = x.to_a.last(7).to_h
然后y
是
{
"01/09"=>{:a=>2, :b=>9},
"02/09"=>{:a=>0, :b=>3},
"04/09"=>{:a=>0, :b=>4},
"06/09"=>{:a=>0, :b=>26},
"07/09"=>{:a=>0, :b=>2},
"06/10"=>{:a=>0, :b=>1},
"07/11"=>{:a=>0, :b=>1}
}
答案 1 :(得分:1)
不太清楚,但这也许可以帮上忙。
要获取前七个values:
h.values.first(7) # or h.values.take(7)
# => [{:a=>0, :b=>2}, {:a=>1, :b=>0}, {:a=>26, :b=>32}, {:a=>2, :b=>9}, {:a=>0, :b=>3}, {:a=>0, :b=>4}, {:a=>0, :b=>26}]
要获取前七个keys:
h.keys.first(7) # => ["01/01", "01/05", "31/08", "01/09", "02/09", "04/09", "06/09"]
或者仅获得first七个元素,如注释中已经指出的那样:
h.first(7).to_h
# {"01/01"=>{:a=>0, :b=>2}, "01/05"=>{:a=>1, :b=>0}, "31/08"=>{:a=>26, :b=>32}, "01/09"=>{:a=>2, :b=>9}, "02/09"=>{:a=>0, :b=>3}, "04/09"=>{:a=>0, :b=>4}, "06/09"=>{:a=>0, :b=>26}}
编辑:从头到尾获取最后七个
h.values.last(7).reverse # => [{:a=>0, :b=>1}, {:a=>0, :b=>1}, {:a=>0, :b=>2}, {:a=>0, :b=>26}, {:a=>0, :b=>4}, {:a=>0, :b=>3}, {:a=>2, :b=>9}]
答案 2 :(得分:1)
您可以将Hash#select与计数器一起使用。
h = {
"01/01"=>{:a=>0, :b=>2},
"01/05"=>{:a=>1, :b=>0},
"31/08"=>{:a=>26, :b=>32},
"01/09"=>{:a=>2, :b=>9},
"02/09"=>{:a=>0, :b=>3},
"04/09"=>{:a=>0, :b=>4},
"06/09"=>{:a=>0, :b=>26},
"07/09"=>{:a=>0, :b=>2},
"06/10"=>{:a=>0, :b=>1},
"07/11"=>{:a=>0, :b=>1}
}
n = 7
h.select { (n-=1) >= 0 }
#=> {"01/01"=>{:a=>0, :b=>2},
# "01/05"=>{:a=>1, :b=>0},
# "31/08"=>{:a=>26, :b=>32},
# "01/09"=>{:a=>2, :b=>9},
# "02/09"=>{:a=>0, :b=>3},
# "04/09"=>{:a=>0, :b=>4},
# "06/09"=>{:a=>0, :b=>26}}