public
Created

Ruby case statements

  • Download Gist
case.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.