代码之家  ›  专栏  ›  技术社区  ›  Tomas.R

案例陈述-Ruby

  •  1
  • Tomas.R  · 技术社区  · 5 年前

    我正在写一个简单的方法来计算我租车需要付多少钱。 然而,当我执行它时,它总是返回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
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   razvans    5 年前

    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
    

    如果你想用 案例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 更多示例。

    推荐文章