Skip to content

Instantly share code, notes, and snippets.

@superacidjax
Created June 11, 2013 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superacidjax/5757121 to your computer and use it in GitHub Desktop.
Save superacidjax/5757121 to your computer and use it in GitHub Desktop.
Brian's Ruby Tuesday: Examples of Case
# case is a multi-way decision statement similar to if/elsif/else
# here's a bit longer and more thorough discussion: http://www.skorks.com/2009/08/how-a-ruby-case-statement-works-and-what-you-can-do-with-it/
# a simple example of case
case title
when 'War and Peace'
puts 'Tolstoy'
when 'Romeo and Juliet'
puts 'Shakespeare'
else
puts "Don't know"
end
# this uses case to assign the value of a variable
author = case title
when 'War and Peace'
'Tolstoy'
when 'Romeo and Juliet'
'Shakespeare'
else
"Don't know"
end
# a more compact version, this is probably better code from a readability standpoint.
# Don't compact methods if it make the code more difficult to read!
# Definitely compact methods if it improves readability, as in this example.
author = case title
when 'War and Peace' then 'Tolstoy'
when 'Romeo and Juliet' then 'Shakespeare'
else "Don't know"
end
# the following returns nil if no value matches, remember nearly everything in Ruby returns a value!
author = case title
when 'War and Peace' then 'Tolstoy'
when 'Romeo and Juliet' then 'Shakespeare'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment