首页 > 解决方案 > 案例陈述 - 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

标签: rubycase

解决方案


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 帖子以获取更多示例。


推荐阅读