如何解决案例陈述 - Ruby
我正在编写一个简单的方法来计算我需要支付多少租车费用。 但是,当我执行它时,它总是返回 else 语句 "nothing" 。这里有什么问题?
def rental_car_cost(d)
case d
when d < 3
puts d * 40
when d >=3 && d < 7
puts d * 40 - 20
when d >= 7
puts d * 40 - 50
else
puts "nothing"
end
end
rental_car_cost(5)
nothing
解决方法
case d
需要 when
中的单个值,而不是条件。
def rental_car_cost(d)
case
when d < 3
puts d * 40
when d >=3 && d < 7
puts d * 40 - 20
when d >= 7
puts d * 40 - 50
else
puts "nothing"
end
end
如果你想使用 case d
那么你应该有这样的东西:
def rental_car_cost(d)
case d
when 3
puts d * 40
when 7
puts d * 40 - 20
else
puts "nothing"
end
end
查看此 SO post 以获取更多示例。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。