首页 > 解决方案 > 根据 if 语句添加到实例?

问题描述

我是一名新的编码员,试图在 ruby​​ 中创建一个简单的“造剑”终端应用程序。所以我有一个类,其中包含一些我想根据用户输入(@strength 和@speed)迭代的实例变量。所以在这里,如果用户输入握把是“直的”,我希望它将实例变量“强度”增加 5 - 但由于某种原因,无论我做什么,它都不会对其进行编辑。我已经将“强度”设置为 attr_accessor,并且我也尝试过手动制作该方法 - 但我仍然无法对其进行迭代。我究竟做错了什么?

class Weapon
    attr_reader :id, :weapon_name, :guard, :blade
    attr_accessor :grip, :strength, :speed

    SWORDS = []

    def initialize(weapon_name, grip, guard, blade)
        @id = SWORDS.length + 1
        @weapon_name = weapon_name
        @grip = grip.to_str
        @guard = guard
        @blade = blade
        @strength = 0
        @speed = 0
        SWORDS << self
    end

    def strength=(strength)
        if @grip == "straight"
            @strength = strength + 5
        end
    end
    
    def to_s
        
        "Your weapon is called: #{@weapon_name}
            The grip is: #{@grip}
            The guard is: #{@guard}
            The blade is: #{@blade}
            Total stats are: Strength = #{@strength} and Speed = #{@speed}"
    
    end
end

标签: ruby

解决方案


仅当您引用类上的名称时才调用访问器。

@strength = 0

这不调用访问器。曾经。即使定义了一个。

self.strength = 0

这将调用访问器。现在,attr_accessor定义strengthstrength=。如果您打算strength=自己编写,那么您需要attr_reader,这并没有strength=为您定义。

class Weapon
  attr_reader :strength

  def initialize()
    ...
    self.strength = 0
  end

  ...

  def strength=(value)
    ...
  end

end

推荐阅读