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 trialArthur Yu
Courses Plus Student 516 PointsIf statement vs Case statement
How would this favorite number program look if it was written via case statement instead?
print "What is your favorite number? "
number = gets.chomp.to_i
if (number == 3) || (number == 5)
puts "That's my favorite number!"
elsif (number > 10) && (number.even?)
puts "That's a pretty high even number!"
elsif (number.odd?) && (number % 3 == 0)
puts "That number is divisible by 3 and odd, cool!"
end
2 Answers
Nick Fuller
9,027 PointsHere is how I would do it!
Introduction to lambdas! http://ruby-doc.org/core-2.1.0/Proc.html#method-i-lambda-3F
However this is a little bit messy. I also added a check at the end.. I like to follow a rule: All if statements, that contain more than one else, and all case statements should have an else. Try not to finish with an 'elsif' or a 'when'.
print "What is your favorite number? "
number = gets.chomp.to_i
def large_even_number(number)
number > 10 && number.even?
end
def odd_divisible_by_three(number)
number % 3 == 0 && number.odd?
end
case number
when 3, 5
then puts "That's my favorite number!"
when ->(n) { large_even_number(n) }
then puts "That's a pretty high even number!"
when ->(n) { odd_divisible_by_three(n) }
then puts "That number is divisible by 3 and odd, cool!"
else
puts "Yuck give me a number man!"
end
Nick Fuller
9,027 PointsOH oh oh I think I got it now!!!!!