Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Gustavo Winter
PLUS
Gustavo Winter
Courses Plus Student 27,382 Points

The statement "Case / When". Can i use arrow on that?

Hello. My doubt is if i can use arrow in these statements, like >= , >, <=, <, etc.

By the way, i check the Ruby-doc and dont find the answer for this.

http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-case

thanks

Joe Purdy
Joe Purdy
23,237 Points

Hey Gustavo!

You can use greater than/less than operators on a case statement, but there isn't an idiomatic use case for them that I can see since these operators evaluate as boolean true/false values.

Take a look at this example:

puts "Enter x: "
x = gets.chomp.to_i

puts "Enter y: "
y = gets.chomp.to_i

case x > y
when true
  puts "#{x} is greater than #{y}"
when false
  puts "#{x} is less than #{y}"
end

This case/when script does behave as expected comparing the entered x and y values and printing whether x was greater than or less than y, but there's no need for a case statement here since there are only two possible return values, true or false. Instead you could simply use an if/else like this:

puts "Enter x: "
x = gets.chomp.to_i

puts "Enter y: "
y = gets.chomp.to_i

if x > y
  puts "#{x} is greater than #{y}"
else
  puts "#{x} is less than #{y}"
end

Case statements really shine best when you have 3 or more conditions since boolean conditions are simply covered in a basic if/else. Using greater than/less than operations is going to return a boolean so I can't think of a situation where I'd want to use them in a case statement.

I hope that helps and if you're dealing with a specific problem or situation where you want to use these types of operators in a case statement can you elaborate in more detail?

1 Answer