我在我的班级Dog中创建了check_dog方法,检查狗是否接种过疫苗或蠕虫病毒。
但是,我发现很难想到这个语句If the dog is only vaccinated or only wormed, the dog can only be accepted by itself.
你可以在下面看到我缩进了我需要帮助的行,因为这行导致'nil'。
class Dog
attr_accessor :name, :age, :breed, :vaccinated, :wormed
def initialize(name, age, breed, vaccinated, wormed)
@name = name
@age = age
@breed = breed
@vaccinated = vaccinated
@wormed = wormed
end
def check_dog
if @vaccinated && @wormed == true
puts "#{@name} can be accepted"
----> elsif @vaccinated || @wormed == true
puts "#{@name} can only be accepted by itself"
else
puts "#{@name} cannot be accepted"
end
end
end
spot = Dog.new("Spot", 5, "Labrador", true, false)
spot.check_dog # Should return: "Spot can only be accepted by itself".
答案 0 :(得分:2)
def check_dog
case [@vaccinated, @wormed]
when [true, true] then "#{@name} can be accepted"
when [false, false] then "#{@name} cannot be accepted"
else "#{@name} can only be accepted by itself"
end.tap(&method(:puts))
end
这样打印并返回result
。
答案 1 :(得分:1)
你写它的方式看起来不正确...使用你的风格应该看起来像这样:
def check_dog
if @vaccinated == true && @wormed == true
puts "#{@name} can be accepted"
elsif @vaccinated == true || @wormed == true
puts "#{@name} can only be accepted by itself"
else
puts "#{@name} cannot be accepted"
end
end
为了更简单,你可以这样做
def check_dog
if @vaccinated && @wormed # both are truthy
puts "#{@name} can be accepted"
elsif @vaccinated || @wormed # one or the other are truthy
puts "#{@name} can only be accepted by itself"
else # falsey
puts "#{@name} cannot be accepted"
end
end
另请注意,该方法实际上是返回nil
..您没有返回任何内容,而是输出到stdout
...尝试将代码更改为:
def check_dog
if @vaccinated && @wormed # both are truthy
"#{@name} can be accepted"
elsif @vaccinated || @wormed # one or the other are truthy
"#{@name} can only be accepted by itself"
else # falsey
"#{@name} cannot be accepted"
end
end