2

私はまだRubyを学んでおり、このシナリオでクラス変数、定数、またはローカル変数を使用することが適切かどうかについて興味があります。

以下のコード例(固定文字セットからランダムなユーザー名を生成する)では@username、インスタンス変数として割り当てるのはかなり明白です。しかし、文字セットを定数として割り当てるのか、クラス変数として割り当てるのかが気になります。このシナリオで別の変数タイプを使用する利点は何ですか?

現在の例では、_charsetはすべてのインスタンスで計算されます。(私の仮定が間違っている場合は訂正してください。)また、計算はクラス変数と定数の両方として(再計算ではなく)インスタンス間で共有されると仮定しますか?

class NewAccount

  def initialize
    @username = self.generate_username
  end

  def generate_username
    _charset = ('a'..'z').to_a + ('0'..'9').to_a
    _newusername = Array.new(20) { _charset[rand(_charset.length)] }.join
    return _newusername
  end

end
4

4 に答える 4

3

You can make it a class variable or constant, actually this would be the same: only one instance would exist. And Ruby constants are not really constants - you can change a constant so it is really a variable, only because of its name Ruby recognizes a constant and issue a warning if you try to change it.

But by declaring it as a constant and not a class variable you are documenting your aim: to have a constant value consisting of a character set, that is not designed to be changed. This will be obvious for anybody reading the code. This is what you want the character set for - so do it.

If you make it a class variable it will be a variable: so no problem if somebody tries to change. Of course if you plan on changing its value for whatever reason do it a class variable: again you will document your design.

于 2011-04-30T20:15:49.693 に答える
2

その定義から変更されることはないため_charset = ('a'..'z').to_a + ('0'..'9').to_a、クラス定数として作成します。

class NewAccount

  CHARSET = ('a'..'z').to_a + ('0'..'9').to_a

  def initialize
    @username = self.generate_username
  end

  def generate_username
    _newusername = Array.new(20) { CHARSET[rand(CHARSET.length)] }.join
    return _newusername
  end

end
于 2011-04-30T21:38:57.077 に答える
1

この例では、@ usernameはインスタンスごとに1回計算され、_charsetは例で1回だけ計算されますが、_charsetはローカル変数にすぎないため、メソッドを2回実行すると再計算されます。

必要なのは、Tin Manが提案するものであり、定数として設定し、一度計算します。class-varible(@@ charset)を使用すると、文字セットはどの時点でも変更されることを意図していないため、誤解を招く可能性があります。

于 2011-05-01T14:20:59.000 に答える
1

_charset は NewAccount クラスでのみ使用され、その値は NewAccount のインスタンスでは変更されないため、クラス変数にすることができると思います。

于 2011-04-30T20:03:19.670 に答える