04 - using an array or other modifiable object as a hash key.rb
来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 44 行
RB
44 行
coordinates = [10, 5]treasure_map = { coordinates => 'jewels' }treasure_map[coordinates] # => "jewels"# Add a z-coordinate to indicate how deep the treasure is buried.coordinates << -5coordinates # => [10, 5, -5]treasure_map[coordinates] # => nil# Oh no!#---treasure_map.rehashtreasure_map[coordinates] # => "jewels"#---module ReliablyHashable def hash return object_id endendclass ReliablyHashableArray < Array include ReliablyHashableend#---coordinates = ReliablyHashableArray.new([10,5])treasure_map = { coordinates => 'jewels' }treasure_map[coordinates] # => "jewels"# Add a z-coordinate to indicate how deep the treasure is buried.coordinates.push(-5)treasure_map[coordinates] # => "jewels"#---a = [1,2]b = a.clonea.hash # => 11b.hash # => 11a = ReliablyHashableArray.new([1,2])b = a.clonea.hash # => -606031406b.hash # => -606034266#---
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?