为什么有时必须用 @ 有时不用 @ 来引用您的类属性?如果我要删除“@completed”并替换为“completed”,测试将失败。但是在 Project 类中,tasks 属性的设置方式相同,但可以在没有 @ 的情况下使用。
class Task
attr_accessor :size, :completed
def initialize(options = {})
@completed = options[:completed]
@size = options[:size]
end
def completed?
@completed
end
def mark_completed
@completed = true
end
end
class Project
attr_accessor :tasks
def initialize
@tasks = []
end
def done?
tasks.reject(&:completed?).empty?
end
def total_size
tasks.sum(&:size)
end
def remaining_size
tasks.reject(&:completed?).sum(&:size)
end
end
describe "estimates" do
let (:project) { Project.new }
let (:done) { Task.new(size: 2, completed: true) }
let(:small_not_done) { Task.new(size: 1) }
let(:large_none_done) { Task.new(size: 4) }
before(:example) do
project.tasks = [done, small_not_done, large_none_done]
end
it "can calculate total size" do
expect(project.total_size).to eq(7)
end
it "can calculate remaining size" do
expect(project.remaining_size).to eq(5)
end
end
最佳答案
attr_accessor :tasks
等同于:
def tasks
@tasks
end
def tasks=(val)
@tasks = val
end
当您调用tasks
时,您正在调用tasks
方法,它只返回@tasks
变量的值。访问器方法总是在类的外部使用(因为实例变量不可见),但您可以在类内使用,因为它们在功能上是等价的这个任务方法的实现。但是,如果您可能除了返回 @tasks
之外还要做其他事情,您可能想要使用 tasks
访问器 - 通过隐藏方法后面的变量访问,您可以自由地 future 可以在该访问器中完成更复杂的工作,而无需更改您使用它的地方。
关于ruby-on-rails - 在 Ruby on Rails 中@或不@,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31359424/