我有一个哈希,其中的键是0、3和5,值是散列。
{0=>{:occurrences=>1, :className=>"class"},
3=>{:occurrences=>3, :className=>"hello"},
5=>{:occurrences=>3, :className=>"nah"}}
我该如何实现这样的东西:
h.map { |key|
if key[:occurrences] > 2
key[:occurrences] += 1
end
}
我知道此语法无效。我想在满足条件时增加出现值,并且不确定如何访问键的键,但是我希望结果是:
{0=>{:occurrences=>1, :className=>"class"},
3=>{:occurrences=>4, :className=>"hello"},
5=>{:occurrences=>4, :className=>"nah"}}
答案 0 :(得分:1)
只是出于好奇:
input.map do |k, v|
[k, v[:occurrences].to_i > 2 ? v.merge(occurrences: v[:occurrences] + 1) : v]
end.to_h
#⇒ {0=>{:occurrence=>1, :className=>"class"},
# 3=>{:occurrences=>4, :className=>"hello"},
# 5=>{:occurrences=>4, :className=>"nah"}}
答案 1 :(得分:1)
要更新现有哈希,您可以简单地调用each_value
。它将哈希中的每个值传递给该块,并且您可以在该块内更新该值(基于条件):
h = {
0=>{:occurrences=>1, :className=>"class"},
3=>{:occurrences=>3, :className=>"hello"},
5=>{:occurrences=>3, :className=>"nah"}
}
h.each_value { |v| v[:occurrences] += 1 if v[:occurrences] > 2 }
#=> {
# 0=>{:occurrences=>1, :className=>"class"},
# 3=>{:occurrences=>4, :className=>"hello"},
# 5=>{:occurrences=>4, :className=>"nah"}
# }
答案 2 :(得分:1)
h = { 0=>{ :occurrences=>1, :className=>"class" },
3=>{ :occurrences=>3, :className=>"hello" },
5=>{ :occurrences=>3, :className=>"nah" } }
f = h.dup
非破坏性案件
h.transform_values do |g|
g[:occurrences] > 2 ? g.merge(occurrences: g[:occurrences] + 1) : g
end
#=> { 0=>{ :occurrences=>1, :className=>"class" },
# 3=>{ :occurrences=>4, :className=>"hello" },
# 5=>{ :occurrences=>4, :className=>"nah" } }
h == f
#=> true
破坏性案件
g = h.transform_values! do |g|
g[:occurrences] > 2 ? g.merge(occurrences: g[:occurrences] + 1) : g
end
#=> { 0=>{ :occurrences=>1, :className=>"class" },
# 3=>{ :occurrences=>4, :className=>"hello" },
# 5=>{ :occurrences=>4, :className=>"nah" } }
h == g
请参见Hash#transform_values和Hash#transform_values!,它们在MRI v.2.4中首次亮相。请注意,在破坏性情况下,不需要merge!
。
答案 3 :(得分:0)
例如,我希望返回整个散列,但已更新 值:{0 => {:occurrence => 1,:className =>“ class”}, 3 => {:occurrences => 4,:className =>“ hello”},5 => {:occurrences => 4, :className =>“ nah”}}。如果出现键的值更大 比我想增加该值还多两个 哈希。
您在这里:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
view.clusteringIdentifier = nil
}