Skip to content

Instantly share code, notes, and snippets.

@jbrechtel
Created August 21, 2011 16:37
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 jbrechtel/1160828 to your computer and use it in GitHub Desktop.
Save jbrechtel/1160828 to your computer and use it in GitHub Desktop.
Ruby case statements
#execute a different method based on a variable value
name = ask_for_name()
case name
when 'bill'
email_report()
when 'thomas'
print_report()
when 'ted'
fax_report()
when 'james'
rsync_report()
end
#return a value from a case statement
location = ask_for_location()
address = case location
when 'home'
'555 Main St. Gulfport, MS 39503'
when 'office'
'930 28th St. Long Beach, MS 39520'
when 'school'
'200 Highway 90 Long Beach, MS 39520'
end
#match value based on regex
#extract middle name, if one was given.
#if one wasn't given then assume it should be Peatrice
middle_name = case full_name
when /^.*\s(.*)\s.*$/
$1
else
"Peatrice"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment