sammms
sammms

Reputation: 677

Effecient way to find key name in hash with only one key in Ruby?

I have an array of hashes, each hash containing only one key/value pair. is there a more efficient way of accessing the key? This is my ugly solution

array_of_hashes = [
  {:some => "stuff"},
  {:other => "stuff"}
  ]

array_of_hashes.each do |hash|
  hash.each do |key, value|
    puts key
end

it seems like to me there must be some way of simply saying

array_of_hashes.each do |hash|
  puts hash.key # where this would simply access the key
end

or possibly

array_of_hashes.each do |hash|
  puts hash.keys[0]
end

but that still feels a bit sloppy.

Upvotes: 0

Views: 1339

Answers (1)

Jesper
Jesper

Reputation: 4555

I'm not sure what kind of efficiency you're after, but this at least is very short:

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

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

Upvotes: 2

Related Questions