ruby cookbook -- Hash

Hash
1. Except for strings and other built-in objects, most objects have a hash code equivalent to their internal object ID. As seen above, you can override Object#hash to change this, but the only time you should need to do this is if your class also overrides Object#==. If two objects are considered equal, they should also have the same hash code; otherwise, they will behave strangely when you put them into hashes. Code like the fragment below is a very good idea:

class StringHolder
attr_reader :string
def initialize(s)
@string = s
end

def ==(other)
@string == other.string
end

def hash
@string.hash
end
end
a = StringHolder.new("The same string.")
b = StringHolder.new("The same string.")
a == b # => true
a.hash # => -1007666862
b.hash # => -1007666862

Except for strings and other built-in objects, most objects have a hash code equivalent to their internal object ID. As seen above, you can override Object#hash to change this, but the only time you should need to do this is if your class also overrides Object#==. If two objects are considered equal, they should also have the same hash code; otherwise, they will behave strangely when you put them into hashes. Code like the fragment below is a very good idea:

class StringHolder
attr_reader :string
def initialize(s)
@string = s
end

def ==(other)
@string == other.string
end

def hash
@string.hash
end
end
a = StringHolder.new("The same string.")
b = StringHolder.new("The same string.")
a == b # => true
a.hash # => -1007666862
b.hash # => -1007666862

Using Symbols as Hash Keys
While 'name' and 'name' appear exactly identical, they're actually different. Each time you create a quoted string in Ruby, you create a unique object. You can see this by looking at the object_id method.

'name'.object_id # => -605973716
'name'.object_id # => -605976356
'name'.object_id # => -605978996

By comparison, each instance of a symbol refers to a single object.

:name.object_id # => 878862
:name.object_id # => 878862
'name'.intern.object_id # => 878862
'name'.intern.object_id # => 878862

Using symbols instead of strings saves memory and time. It saves memory because there's only one symbol instance, instead of many string instances. If you have many hashes that contain the same keys, the memory savings adds up.

Using symbols as hash keys is faster because the hash value of a symbol is simply its object ID. If you use strings in a hash, Ruby must calculate the hash value of a string each time it's used as a hash key.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值