case when in ruby

In Ruby, there is no direct case when syntax, but you can achieve the same functionality using the case statement. Here is an example:

main.rb
grade = 'A'

case grade
when 'A'
  puts 'Excellent!'
when 'B', 'C'
  puts 'Well done!'
when 'D'
  puts 'You passed!'
when 'F'
  puts 'Better luck next time!'
else
  puts 'Invalid grade'
end
190 chars
15 lines

In this example, we have a variable grade which represents a letter grade. The case statement evaluates the value of grade against various conditions using the when keyword.

If the value of grade matches 'A', it will execute the code inside the corresponding when 'A' block. Similarly, for B and C, D, and F grades. If none of the conditions match, the code inside the else block will be executed.

Note that you can also use multiple values separated by commas, as shown in the when 'B', 'C' line.

Hope this helps!

related categories

gistlibby LogSnag