ruby - 根据 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
解决方案
仅当您引用类上的名称时才调用访问器。
@strength = 0
这不调用访问器。曾经。即使定义了一个。
self.strength = 0
这将调用访问器。现在,attr_accessor
定义strength
和strength=
。如果您打算strength=
自己编写,那么您需要attr_reader
,这并没有strength=
为您定义。
class Weapon
attr_reader :strength
def initialize()
...
self.strength = 0
end
...
def strength=(value)
...
end
end
推荐阅读
- javascript - 如何在包裹 js 中包含资产文件?
- java - 未找到 ClientRegistrationRepository Bean
- angular - 在 Angular 中安装 Jest 时无法读取未定义的属性“匹配项”
- html - 悬停时在右侧元素列表中添加图像
- php - 我从页面速度洞察中得到一个错误
- python - 有没有办法在linux中更新python 3.6
- html - 拉伸背景图像以占据 div 的全高
- javascript - 如何从“font.googleapis”中查找和复制链接
- python - 检查是否可以在 Python 中使用递归来均衡整数数组
- javascript - 员工模型的自定义方法-backbone.js 一个测试用例失败