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.
81b61a7cc07af1779b2d7ca9fbe17e0c?d=identicon&s=25 Selim Selim007 (selim007)
on 2008-12-20 12: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
699c00ad35f2755810b4aa5f423d73e2?d=identicon&s=25 Albert Schlef (alby)
on 2008-12-24 17: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" ?
E8a419959139f3f505b49bb95f7e7afe?d=identicon&s=25 Joshua Ballanco (jballanc)
on 2008-12-24 18:45
Albert Schlef 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
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2008-12-25 11: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.