1

I'm writing a simple method which counts how much I need to pay for renting a car. However when I execute it, it always return else statement "nothing" . What is wrong here ?

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
Tomas.R
  • 715
  • 2
  • 7
  • 18
  • In such a scenario you're probably better of using an [if-statement](https://docs.ruby-lang.org/en/3.0.0/doc/syntax/control_expressions_rdoc.html#label-if+Expression) with `elsif` conditions. – 3limin4t0r Mar 21 '21 at 12:40
  • thank you for your response, I will look at it. – Tomas.R Mar 21 '21 at 12:45

1 Answers1

1

case d expects single values in when, not conditions.

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

If you want to use case d then you should have something like this:

def rental_car_cost(d)
  case d
  when 3
    puts d * 40
  when 7
    puts d * 40 - 20
  else
    puts "nothing"
  end
end

Check this SO post for more examples.

razvans
  • 3,172
  • 7
  • 22
  • 30