mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
add Hash#rehash to handle key modification; ref #2945
This commit is contained in:
@@ -319,6 +319,29 @@ class Hash
|
||||
h
|
||||
end
|
||||
|
||||
##
|
||||
# call-seq:
|
||||
# hsh.rehash -> hsh
|
||||
#
|
||||
# Rebuilds the hash based on the current hash values for each key. If
|
||||
# values of key objects have changed since they were inserted, this
|
||||
# method will reindex <i>hsh</i>.
|
||||
#
|
||||
# h = {"AAA" => "b"}
|
||||
# h.keys[0].chop!
|
||||
# h #=> {"AA"=>"b"}
|
||||
# h["AA"] #=> nil
|
||||
# h.rehash #=> {"AA"=>"b"}
|
||||
# h["AA"] #=> "b"
|
||||
#
|
||||
def rehash
|
||||
h = {}
|
||||
self.each{|k,v|
|
||||
h[k] = v
|
||||
}
|
||||
self.replace(h)
|
||||
end
|
||||
|
||||
def __update(h)
|
||||
h.each_key{|k| self[k] = h[k]}
|
||||
self
|
||||
|
||||
@@ -342,3 +342,12 @@ assert('Hash#inspect') do
|
||||
assert_include ret, '"a"=>100'
|
||||
assert_include ret, '"d"=>400'
|
||||
end
|
||||
|
||||
assert('Hash#rehash') do
|
||||
h = {[:a] => "b"}
|
||||
# hash key modified
|
||||
h.keys[0][0] = :b
|
||||
# h[[:b]] => nil
|
||||
h.rehash
|
||||
assert_equal("b", h[[:b]])
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user