Menu
CoddyTech

Conditional Values

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

Java if is a statement, while a ternary expression can select a value. Ruby if itself yields the selected branch's final expression. Java enforces type rules on the conditional result, whereas Ruby determines behavior dynamically when the value is used. Only the selected branch executes in either example.

Java: complete program

import java.util.*;
public class Main {

  public static void main(String[] args) {
    boolean wet = false;
    String icon = wet ? "umbrella" : "sun";
    System.out.println(icon);
  }
}

Ruby: complete program

wet = false
icon = if wet
  "umbrella"
else
  "sun"
end
puts icon
challenge icon

Challenge

Easy

Input is integer distance 0..1000. Return delivery fee: 0 for distance zero, 5 for 1..10, 9 for 11..50, 15 above 50.

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