LoginSignup
4
4

More than 5 years have passed since last update.

一度でも偽になるとその後代入不可能になるプロパティ

Posted at

Rubyでは||=が出来るので、当然&&=も出来るよね
と言うことで実験してみました。

class Hoge
  def initialize
    @a = 0
  end

  def a=(i)
    @a &&= i
  end

  def a
    @a
  end
end

で、

num = Hoge.new

num.a = 1
p num.a
#=> 1

num.a = 2
p num.a
#=> 2

num.a = nil
p num.a
#=> nil

num.a = 3
p num.a
#=> nil

これだけだとちょっと用途が思いつきませんが、代入メソッドの中にバリデーションのロジックなんかを仕込むと使い道があるかも。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4