Lesson 9 of 15

Conditionals

Conditionals in Ruby

Ruby's if/elsif/else works like most languages:

score = 85

if score >= 90
  puts "A"
elsif score >= 80
  puts "B"
elsif score >= 70
  puts "C"
else
  puts "F"
end

unless

unless is the opposite of if — it runs when the condition is false:

unless score < 60
  puts "Passing"
end

Inline (Modifier) Form

You can put if or unless at the end of a statement:

puts "Positive" if x > 0
puts "Not zero" unless x == 0

Ternary Operator

status = score >= 60 ? "pass" : "fail"

Your Task

Write a method grade(score) that returns:

  • "A" for scores ≥ 90
  • "B" for scores ≥ 80
  • "C" for scores ≥ 70
  • "F" otherwise

Then print grade(95), grade(82), grade(71), grade(60).

ruby.wasm loading...
Loading...
Click "Run" to execute your code.