我正在通过阅读实用程序员指南编程Ruby来学习Ruby . 我真的很喜欢语法的简洁.
我无法理解=setter方法名称的作用:
def price=(new_price)
@price = new_price
end
Run Code Online (Sandbox Code Playgroud)
该函数定义与此有何不同:
def price(new_price)
Run Code Online (Sandbox Code Playgroud)
有什么区别=?这本书说它可以直接分配.但是,使用普通的setter方法已经没有了=......?
这是课程的其余部分:
class BookInStock
attr_reader :isbn
attr_accessor :price
def initialize(isbn, price)
@isbn = isbn
@price = Float(price)
end
end
book.price = book.price * 0.75
Run Code Online (Sandbox Code Playgroud)
它为您提供了编写代码的"语法糖",如下所示:
class Book
price=(new_price)
@price = new_price
# do something else
end
end
book = Book.new
book.price = 1
Run Code Online (Sandbox Code Playgroud)
此代码将被翻译为
book.price=(1)
Run Code Online (Sandbox Code Playgroud)
实际上attr_writer,attr_accessor方法为您的类生成setter(price=)方法(attr_reader并attr_accessor生成getter方法).
所以你的BookInStock课程类似于:
class BookInStock
def isbn val
@isbn = val
end
def price val
@price
end
def price= val
@price = val
end
def initialize(isbn, price)
@isbn = isbn
@price = Float(price)
end
end
Run Code Online (Sandbox Code Playgroud)
=只有在要添加一些逻辑时才需要编写方法(如验证).在其他情况下,只需使用attr_writer或attr_accessor.