Menu
CoddyTech

Case and Ranges

Lesson 10 of 48 in Coddy's Ruby for Java Developers course.

Java switch behavior depends on statement or expression form and label syntax. Ruby case uses case equality, including range membership, and has no fall-through. Ruby three-dot ranges exclude their endpoint; ordinary Java loops spell out the comparison. These examples avoid assuming that a Java switch can use arbitrary numeric range labels.

Java: complete program

import java.util.*;
public class Main {

  public static void main(String[] args) {
    String letter = "e";
    System.out.println("aeiou".contains(letter) ? "vowel" : "other");
    List<String> values = new ArrayList<>();
    for (int n = 2; n < 5; n++) values.add(Integer.toString(n));
    System.out.println(String.join(" ", values));
  }
}

Ruby: complete program

letter = "e"
puts(case letter
when "a", "e", "i", "o", "u" then "vowel"
else "other"
end)
puts (2...5).to_a.join(" ")
challenge icon

Challenge

Easy

Read an integer score 0..100. Return low for 0..39, middle for 40..79, high for 80..100.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
def check(value)
  raise 'Public API check failed' unless value
end

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for Java Developers

Practice on your own: Online Ruby compiler