在 Ruby 中只用一个键在散列中查找键名的有效方法?
Effecient way to find key name in hash with only one key in Ruby?
我有一个哈希数组,每个哈希只包含一对 key/value。有没有更有效的访问密钥的方法?这是我丑陋的解决方案
array_of_hashes = [
{:some => "stuff"},
{:other => "stuff"}
]
array_of_hashes.each do |hash|
hash.each do |key, value|
puts key
end
在我看来,必须有某种简单的说法
array_of_hashes.each do |hash|
puts hash.key # where this would simply access the key
end
或者可能
array_of_hashes.each do |hash|
puts hash.keys[0]
end
但这仍然感觉有点草率。
我不确定你追求的是哪种效率,但这至少是很短的:
hashes = [
{ a: 'a'},
{ b: 'b'},
{ c: 'c'}
]
hashes.flat_map(&:keys)
# => [:a, :b, :c]
我有一个哈希数组,每个哈希只包含一对 key/value。有没有更有效的访问密钥的方法?这是我丑陋的解决方案
array_of_hashes = [
{:some => "stuff"},
{:other => "stuff"}
]
array_of_hashes.each do |hash|
hash.each do |key, value|
puts key
end
在我看来,必须有某种简单的说法
array_of_hashes.each do |hash|
puts hash.key # where this would simply access the key
end
或者可能
array_of_hashes.each do |hash|
puts hash.keys[0]
end
但这仍然感觉有点草率。
我不确定你追求的是哪种效率,但这至少是很短的:
hashes = [
{ a: 'a'},
{ b: 'b'},
{ c: 'c'}
]
hashes.flat_map(&:keys)
# => [:a, :b, :c]