【问题标题】:Effecient way to find key name in hash with only one key in Ruby?在Ruby中只有一个键在哈希中查找键名的有效方法?
【发布时间】:2016-06-11 19:12:51
【问题描述】:

我有一个哈希数组,每个哈希只包含一个键/值对。有没有更有效的方法来访问密钥?这是我丑陋的解决方案

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

但这仍然感觉有点草率。

【问题讨论】:

  • array_of_hashes.each { |h| puts h.first.first }
  • 谢谢,我想这就是我的第二个选择:

标签: ruby hash key


【解决方案1】:

我不确定你追求什么样的效率,但这至少很短:

hashes = [
  { a: 'a'},
  { b: 'b'},
  { c: 'c'}
]

hashes.flat_map(&:keys)
# => [:a, :b, :c]

【讨论】:

  • 这意味着您必须创建数组,然后puts 它,但这通常比putsing 每个元素(而不是创建数组)更好,因为您以后可能需要数组. putsing 每个元素在调试时都很好,当然,在这种情况下,@mudasobwa 的建议就可以了。
  • 谢谢。为了澄清,我正在寻找一种在语法上更清晰的方法,它对于只有一个键值对的哈希,而不是假设多个元素的方法。它甚至可能不存在,因为哈希通常具有多个元素,但由于我是新手,我认为我应该检查一下。感谢您的帮助!
猜你喜欢
  • 2011-10-25
  • 2017-03-31
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多