ActiveRecordで属性を定義する場合、次のメソッドを使用できます
# gets the value for needs_review
def needs_review
end
# sets the value for needs_review
def needs_review=(value)
end
セッターはを使用して呼び出すことができます
needs_review = "hello"
ただし、これは変数を設定するのと同じ方法です。メソッド内でステートメントを呼び出すと、Rubyは変数の割り当てを優先するため、その名前の変数が作成されます。
def one
# variable needs_review created with value foo
needs_review = "foo"
needs_review
end
one
# => returns the value of the variable
def two
needs_review
end
two
# => returns the value of the method needs_review
# because no variable needs_review exists in the context
# of the method
経験則として:
self.method_name =
メソッド内でセッターを呼び出したい場合は常に使用します
- オプション
self.method_name
で、同じ名前のローカル変数がコンテキストに存在する場合に使用します