문제

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