检查适用于小于0或大于100的整数。但有人可以告诉我为什么“不允许字符串”不会被分配给英特尔?
class Human
attr_accessor :intel, :agility, :strength
def initialize(intel, agility, strength)
intel.is_a?(String) ? intel = "string not allowed" : check_range(intel) ? @intel = "Invalid Stat for intel" : @intel = intel
check_range(agility) ? @agility = "Invalid Stat for agility" : @agility = agility
check_range(strength) ? @strength = "Invalid Stat for strength" : @strength = strength
end
def check_range(skill)
skill.to_f < 0 || skill.to_f > 100
end
rosetta = Human.new('twenty,26,39)
puts rosetta.intel, rosetta.agility, rosetta.strength
end
答案 0 :(得分:0)
将 分配给intel
。是不被分配到@intel
,这可能是您的意图?
您可以将该行更改为
@intel = intel.is_a?(String) ? "string not allowed" : check_range(intel) ? "Invalid Stat for intel" : intel
但实际上你的代码需要一些戏剧性的重构。为什么检查String
?其他课程也不会有效吗?为什么要在变量中存储错误消息?