我有一个常规哈希
myhash = { :abc => 123 }
和一个班级
class SpecialHash < Hash
def initialize arg_hash
# how do I say
self = arg_hash
end
end
或
有没有办法: myhash.class = SpecialHash?
-daniel
答案 0 :(得分:1)
最佳解决方案取决于您要扩展的库以及您想要实现的目标。
如果是Hash,很难以这种方式扩展它,因为在使用Ruby哈希语法时没有初始化程序可以覆盖。
但是,因为创建具有某个值的新哈希与将空哈希与给定值合并相同,所以可以
class SpecialHash < Hash
def initialize(hash)
self.merge!(hash)
end
end
myhash = SpecialHash.new(:abc => 123)
myhash
将是SpecialHash
的实例,具有与哈希相同的属性。
请注意使用merge!
实际上正在更改self
的值。使用self.merge
不会产生同样的效果。