1

インスタンス変数を大量に持つ大きなクラスを書くときは、==、eql? と書きます。ハッシュメソッドは大きな面倒です。このプロセスを自動化する「テンプレート クラス」を作成する方法はありますか? または他の方法で。

例:

class Template
    def ==(other)
      //Some way of comparing all of self's instance variables to other's.
    end

    def eql?(other)
      self == other
    end

    def hash
      //Some way of XORing the instance variables of self
    end
end

class Test < Example
    attr_reader :foo
    attr_reader :bar

    def initialize(foo, bar)
      @foo = foo
      @bar = bar
    end
end

a = Test.new "123", "456"
b = Test.new "123", "456"
a == b
> true
4

3 に答える 3

2
Test = Struct.new(:foo, :bar)

a = Test.new "123", "456"
b = Test.new "123", "456"

a == b
# => true
于 2013-09-06T17:18:55.410 に答える
0

Ruby FacetsEquitableモジュールを提供します。これは、探しているものをほぼ正確に提供します。

あなたの例は次のようになります。

class Test
  include Equitable(:foo, :bar)
end

宝石全体を使いたくない場合は、ソースをつかむことができます- それはかなり軽いです。

于 2014-11-08T22:15:00.630 に答える