I'm wondering if there is a more canonical way to do this in ruby 1.9
I have an array with a bunch of objects and I want to group them into a Hash using a property of each object in the array.
Very simplified example:
> sh = {}
=> {}
> aers = %w(a b c d ab bc de abc)
=> ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
> aers.each do |aer|
> sh[aer.size] = [] if sh[aer.size].nil?
> sh[aer.size] << aer
> end
=> ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
> sh
=> {1=>["a", "b", "c", "d"], 2=>["ab", "bc", "de"], 3=>["abc"]}
I tried this, but its output is wrong (as you can see):
sh = Hash.new([])
=> {}
> aers.each do |aer|
> sh[aer.size] << aer
> end
=> ["a", "b", "c", "d", "ab", "bc", "de", "abc"]
> sh
=> {}