On Sat, Nov 12, 2011 at 1:26 AM, Eric Wong <normalperson / yhbt.net> wrote:
> Ryan Davis <ryand-ruby / zenspider.com> wrote:
>> On Nov 11, 2011, at 15:20 , Robert Klemme wrote:
>> > On Fri, Nov 11, 2011 at 10:07 PM, Ryan Davis <ryand-ruby / zenspider.com> wrote:
>> >> On Nov 11, 2011, at 04:50 , Robert Klemme wrote:
>> >>
>> >>> # ensure every word is only once in memory
>> >>> words = Hash.new {|h,k| k.freeze; h[k] = k}
>> >>
>> >> AFAIK, Ruby hashes have (almost) always frozen their keys.
>> >
>> > I know.      
>>
>> I'm confused. If you know that the key is going to be frozen anyways,
>> why freeze it?
>
> The implicit freeze from Hash#[]= duplicates the string and freezes
> the duplicate, not the same object given by the user.
>
> Explicitly freezing the key before Hash#[]= prevents MRI[1] from
> duplicating the string.

Exactly.  And in that case we would end up with two objects in memory
where one is sufficient:

irb(main):008:0> s = "foo"
=> "foo"
irb(main):009:0> h = Hash.new {|ha,k| ha[k]=k}
=> {}
irb(main):010:0> h[s]
=> "foo"
irb(main):011:0> h.each {|k,v| puts k.object_id, v.object_id}
137705420
137645970
=> {"foo"=>"foo"}

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/