# by Greg Houston
# http://ghouston.blogspot.com/
require 'test/unit'
class Test_Hash < Test::Unit::TestCase
def test_hash_clones_string_key
# demonstrates the behavior of Ruby's Hash
#
# when Ruby's Hash gets a String for a key, it appears to create a
# new String with the same contents to use as the original string.
#
# unfortunately any overridden methods in the original string's singleton_class
# are lost to the Hash key.
h = Hash.new
k = "key"
class << k
def foo; 'foo'; end
end
h[k] = "value"
assert( k.respond_to?( :foo ), "k should have singleton_class method #foo" )
assert( !h.keys[0].respond_to?( :foo ), "key should not have singleton_class method #foo" )
ids = h.collect { |key,value| key.object_id }
assert( !ids.include?( k.object_id ), "key in hash should have a different object_id" )
end
end
=begin
>ruby try_hash_string_key.rb
Loaded suite try_hash_string_key
Started
.
Finished in 0.0 seconds.
1 tests, 3 assertions, 0 failures, 0 errors
>Exit code: 0
=end