Ruby case statement – Find output programs (set 1)

This section contains the Ruby case statements find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on February 12, 2022

Program 1:

case 20 when 10 puts "TEN"; when 20 puts "TWENTY"; when 30 puts "THIRTY"; when 40 puts "FORTY"; when 50 puts "FIFTY"; else puts "Unknown number"; end

Output:

TWENTY

Explanation:

In the above program, we created case blocks. Here, the case 20 matched based on the given value and printed the "TWENTY".


Program 2:

case (40-10) when 10 puts "TEN"; when 20 puts "TWENTY"; when 30 puts "THIRTY"; when 40 puts "FORTY"; when 50 puts "FIFTY"; else puts "Unknown number"; end

Output:

THIRTY

Explanation:

In the above program, we created case blocks. Here case 30 matched based on the given value and printed the " THIRTY".


Program 3:

case 40 when 80-10 puts "SEVENTY"; when 80-20 puts "SIXTY"; when 80-30 puts "FIFTY"; when 80-40 puts "FORTY"; when 80-50 puts "THIRTY"; else puts "Unknown number"; end

Output:

FORTY

Explanation:

In the above program, we created case blocks. Here, the case 40 matched based on the given value and printed the "FORTY".


Program 4:

case 40 else puts "Unknown number"; when 10 puts "TEN"; when 20 puts "TWENTY"; when 30 puts "THIRTY"; when 40 puts "FORTY"; when 50 puts "FIFTY"; end

Output:

HelloWorld.rb:2: syntax error, unexpected keyword_else, expecting keyword_when
    else 
    ^~~~
HelloWorld.rb:4: syntax error, unexpected keyword_when, expecting end-of-input
    when 10
    ^~~~

Explanation:

The above program will generate errors because we can use "else" at the end of the "case" statement only. The correct program is given below:

case 40 when 10 puts "TEN"; when 20 puts "TWENTY"; when 30 puts "THIRTY"; when 40 puts "FORTY"; when 50 puts "FIFTY"; else puts "Unknown number"; end # Output: FORTY

Program 5:

case 43 when 11..20 puts "Number is within the range of 11 to 20"; when 21..30 puts "Number is within the range of 21 to 30"; when 31..40 puts "Number is within the range of 31 to 40"; when 41..50 puts "Number is within the range of 41 to 50"; else puts "Unknown number"; end

Output:

Number is within the range of 41 to 50

Explanation:

In the above program, we created case blocks. Here, the case 41..50 matched the given number with range, and print the appropriate message.

Ruby Find Output Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.