سؤال

The objective of the code below is to produce a hash with the keys being the :id field of the hashes in original_array, and the values being all elements in original_array which have that :id.

original_array = [
  {:id => '123', :name => 'test'},
  {:id => '123', :name => 'another test'},
  {:id => '456', :name => 'yet another test'}
]

new_hash = {}
original_array.each do |a|
  new_hash[a[:id]] = original_array.select {|x| x[:id] == a[:id]}
end

My code does that, but there must be some better way to do it, ideally where the hash can be created in one step. If anyone can suggest and explain one (in the hope that I might improve my understanding of this sort of thing), then it would be appreciated.

هل كانت مفيدة؟

المحلول

This should do it

new_hash = original_array.group_by{|h| h[:id]}

Documentation: Enumerable#group_by.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top