Ruby is!


#1

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


#2

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” ?


#3

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


#4

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.