Generally which is better to use?:
case n
when 'foo'
result = 'bar'
when 'peanut butter'
result = 'jelly'
when 'stack'
result = 'overflow'
return result
or
map = {'foo' => 'bar', 'peanut butter' => 'jelly', 'stack' => 'overflow'}
return map[n]
More specifically, when should I use case-statements and when should I simply use a hash?
A hash is a data structure, and a case statement is a control structure.
You should use a hash when you are just retrieving some data (like in the example you provided). If there is additional logic that needs to be performed, you should write a case statement.
Also, if you need to perform some pattern matching, it makes sense to use a case statement:
#pattern matching using ranges
letterGrade = case score
when 0..64 then "F"
when 65..69 then "D"
when 70..79 then "C"
when 80..89 then "B"
when 90..100 then "A"
else "Invalid Score"
end
#pattern matching using regular expressions
case songData
when /title=(.*)/
puts "Song title: #$1"
when /track=(.*)/
puts "Track number: #$1"
when /artist=(.*)/
puts "Artist name: #$1"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With