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

Brandon Jacobi
Brandon Jacobi
4,702 Points

RUBY: Elsif Statements vs Case Statements. Which is better for production?

When using Elsif and Case statements for checking for certain conditions which is better to use?

Elsif

if answer == "reverse"
  puts "This is your name backwards: "
  puts name.reverse
elsif answer == "uppercase"
  puts "This is your name in all uppercase letters: "
  puts name.upcase
elsif answer == "both"
  puts "This is your name in every look: "
  puts name.reverse.upcase
elsif answer == "no"
  puts "Okay then...."
end

Case

case answer
  when "reverse"
    puts "This is your name backwards: "
    puts name.reverse
  when "uppercase"
    puts "This is your name in all uppercase letters: "
    puts name.upcase
  when "both"
    puts "This is your name in every look: "
    puts name.reverse.upcase
  else "no"
    puts "Okay then...."
end

So when it comes down to these which one is better to use? It it just preference?

1 Answer

There's no essential difference between the two and you should be able to use either depending on style. One feature of case expressions is that they return a value. So, you can rewrite your example thusly

puts case answer
  when "reverse"
    "This is your name backwards: "
    name.reverse
  when "uppercase"
    "This is your name in all uppercase letters: "
    name.upcase
  when "both"
    "This is your name in every look: "
    name.reverse.upcase
  else "no"
    "Okay then...."
end