ruby - Ruby 中的虚拟属性

标签 ruby attributes virtual

我正在阅读一个 ruby​​ 教程并尝试使用了解虚拟属性。这是教程中显示的示例。

class Spaceship
  def destination
    @autopilot.destination
  end

  def destination=(new_destination)
    @autopilot.destination = new_destination
  end
end

ship = Spaceship.new
ship.destination = "Earth"
puts ship.destination

根据教程,理想情况下这段代码应该返回 Earth,但我遇到了以下错误。

class.rb:7:in `destination=': undefined method `destination=' for nil:NilClass (NoMethodError) from class.rb:12:in `<main>'

很抱歉,无法识别丢失的部分。

最佳答案

您需要为您的@autopilot 变量分配一些东西。

像这样的东西应该可以工作:

class Spaceship
  def initialize
    @autopilot = Struct.new(:destination).new(nil)
  end

  def destination
    @autopilot.destination
  end

  def destination=(new_destination)
    @autopilot.destination = new_destination
  end
end

但是如果你想添加一个虚拟属性,然后将值保留为一个简单的实例变量,如下所示:

class Spaceship
  def destination
    @destination
  end

  def destination=(new_destination)
    @destination = new_destination
  end
end

关于ruby - Ruby 中的虚拟属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27640051/

相关文章:

ruby - Rakefile - 停止多任务中的每一个任务

java - 为什么我不能从 Java 中另一个包中的继承类调用 protected 方法?

c++ - 不使用虚函数的动机

c++ - 无法将变量 'test' 声明为抽象类型 'OurStack<int>'

C++,为什么基类需要一个VTable

ruby - Heroku 内部服务器错误 - ruby​​/Sinatra/Postgresql

ruby - 部分字符串替换为 gsub

ruby - Ruby 的双冒号 `::` 是什么?

python - 如何确定一个对象在 Python 中是否具有属性?

xslt - 从值中截断字符后的属性总和