Forum: Ruby Ruby is !!!!!!!!!!

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Selim S. (Guest)
on 2008-12-20 13:31
Hello,
I have a text-
class TestStr < String
>   attr_accessor :dupstr
>   def initialize ( str )
>     @dupstr = str
>     super(str)
>   end
> end
> ts=TestStr.new("aaa")
> puts ts.dupstr
> h=Hash.new()
> h[ts]=true
> puts h.keys.first.class
> puts h.keys.first
> puts h.keys.first.dupstr
> ===========================
>
> run it:
>
> $ ruby t.rb
> aaa
> TestStr
> aaa
> nil
> $

http://www.ScoresLive.com
Albert S. (Guest)
on 2008-12-24 18:12
Selim Selim007 wrote:
[...]
>> puts h.keys.first.dupstr

Selim's question is an interesting one.

Could anybody explain why "h.keys.first.dupstr" doesn't return "aaa" ?
Joshua B. (Guest)
on 2008-12-24 19:45
Albert S. wrote:
> Selim Selim007 wrote:
> [...]
>>> puts h.keys.first.dupstr
>
> Selim's question is an interesting one.
>
> Could anybody explain why "h.keys.first.dupstr" doesn't return "aaa" ?

> cat ./test.rb
#!/usr/bin/env ruby -w
class TestStr < String
  attr_accessor :dupstr
  def initialize ( str )
    @dupstr = str
    super(str)
 end
end
ts=TestStr.new("aaa")
puts ts.dupstr
h=Hash.new()
h[ts]=true
puts h.keys.first.class
puts h.keys.first
puts h.keys.first.dupstr
puts h.keys.first.frozen?

> ./test.rb
aaa
TestStr
aaa
nil
true
Brian C. (Guest)
on 2008-12-25 12:50
> Could anybody explain why "h.keys.first.dupstr" doesn't return "aaa" ?

When a Hash key is an unfrozen String, a special case kicks in: a copy
is taken of the key.

irb(main):001:0> key = "foo"
=> "foo"
irb(main):002:0> h = {key => 1}
=> {"foo"=>1}
irb(main):003:0> h.keys
=> ["foo"]
irb(main):004:0> h.keys.first.object_id
=> -605406218
irb(main):005:0> key.object_id
=> -605406278

This avoids a nasty problem if the key is modified after insertion into
the hash. In that case it could end up being on the wrong hash chain and
therefore never be found when looked up.
This topic is locked and can not be replied to.