2级Ruby三元运算符不工作

时间:2014-11-18 04:46:48

标签: ruby ternary-operator

检查适用于小于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 

1 个答案:

答案 0 :(得分:0)

分配给intel。是被分配到@intel,这可能是您的意图?

您可以将该行更改为

@intel = intel.is_a?(String) ? "string not allowed" : check_range(intel) ? "Invalid Stat for intel" : intel

但实际上你的代码需要一些戏剧性的重构。为什么检查String?其他课程也不会有效吗?为什么要在变量中存储错误消息?