Comments on: Memo #3: Advanced usage of Ruby hashes and arrays https://kpumuk.info/ruby-on-rails/memo-3-advanced-usage-of-ruby-hashes-and-arrays/ In my blog I'll try to describe about interesting technologies, my discovery in IT and some useful things about programming. Tue, 14 Jul 2009 07:39:06 +0000 hourly 1 https://wordpress.org/?v=6.7.1 By: Martin https://kpumuk.info/ruby-on-rails/memo-3-advanced-usage-of-ruby-hashes-and-arrays/comment-page-1/#comment-267141 Sun, 25 Jan 2009 17:48:29 +0000 http://kpumuk.info/?p=254#comment-267141 I blogged about it too, a few months ago.

And Ilya Grigorik had an interesting post with some other nice Ruby fu’s.

]]>
By: Peter Szinek https://kpumuk.info/ruby-on-rails/memo-3-advanced-usage-of-ruby-hashes-and-arrays/comment-page-1/#comment-267113 Sun, 25 Jan 2009 10:20:21 +0000 http://kpumuk.info/?p=254#comment-267113 Ah sure… I didn’t notice that the elements of the original array are not unique (should have read the example better, counting the duplicates was the idea… doh)

]]>
By: Dmytro Shteflyuk https://kpumuk.info/ruby-on-rails/memo-3-advanced-usage-of-ruby-hashes-and-arrays/comment-page-1/#comment-267112 Sun, 25 Jan 2009 10:12:46 +0000 http://kpumuk.info/?p=254#comment-267112 Peter, you code would not work. You will got the same array with numbers 1, 2, 3 for all fruits. Hash will be instantiated once and all keys will refer the same instance.

]]>
By: Peter Szinek https://kpumuk.info/ruby-on-rails/memo-3-advanced-usage-of-ruby-hashes-and-arrays/comment-page-1/#comment-267111 Sun, 25 Jan 2009 09:58:55 +0000 http://kpumuk.info/?p=254#comment-267111 Or in this case (i.e. single default value):

1
h = Hash.new([])
]]>
By: Dmytro Shteflyuk https://kpumuk.info/ruby-on-rails/memo-3-advanced-usage-of-ruby-hashes-and-arrays/comment-page-1/#comment-267100 Sun, 25 Jan 2009 07:46:30 +0000 http://kpumuk.info/?p=254#comment-267100 In reply to john.

Wow, it looks much better. Thank you!

]]>
By: john https://kpumuk.info/ruby-on-rails/memo-3-advanced-usage-of-ruby-hashes-and-arrays/comment-page-1/#comment-267076 Sun, 25 Jan 2009 01:59:31 +0000 http://kpumuk.info/?p=254#comment-267076 What about . . . (for your example with h = Hash.new { |h, key| h[key] = [] }):

1
2
3
4
5
6
a = %w(apple banana apple)
h = Hash.new { [] }
a.each_with_index do |fruit, i|
  h[fruit] <<= i
end
puts h.inspect
]]>