2013-12-17 101 views
1

我试图创建一个哈希键的对象。这是我的目标。创建对象的哈希键

def CompositeKey 
    def initialize(name, id) 
     @id=id 
     @name=name 
    end 
end 

然后在同一个文件中,我试图使用它。

def add_to_list(list, obj) 
    # Find or create the payer 
    key = CompositeKey.new(obj["PAYER NAME"], obj['PAYER ID']) 
    payer = list[key] 
    if payer.nil? 
    payer = {} 
    list[key] = payer 
    end 

    # Copy the values into the payer 
    copy_to_payer(obj, payer) 
end 

但我不断收到错误。 rb:57:in 'add_to_list': uninitialized constant CompositeKey (NameError)。 我错过了什么?我如何完成这项工作?

+0

如何使用key.id作为散列键? – Donovan

回答

2

更改“高清”到“类”

class CompositeKey 
... 
end 
1

您需要正确定义类并实现hasheql?方法,否则它不会作为哈希关键工作:

class CompositeKey 

    include Comparable 

    attr_reader :id, :name 

    def initialize(name, id) 
     @id=id 
     @name=name 
    end 

    def hash 
    name.hash 
    end 

    def <=>(other) 
    result = self.id <=> other.id 
    if result == 0 
     self.name <=> other.name 
    else 
     result 
    end 
    end 

end 

通过包括Comparable和实施<=>你就会有正确的eql?==实现你的目标,现在应该是安全哈希键使用。

+1

很好的答案。 <=>可以简单'[self.id,self.name] <=> [other.id,other.name]',或应对轻微DRY违反,创建诸如'state'的方法,该方法返回数组,然后' self.state <=> other.state'。 –

+0

不错,不知道! –

1

如果用于CompositeKey类存在的唯一理由是要哈希键,就可以更简单地使用数组作为重点做到:

key = [obj["PAYER NAME"], obj['PAYER ID']] 

这工作,因为阵列创建自己的哈希键入他们元素的散列键。