Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use hash or case-statement [Ruby]

Tags:

ruby

case

hash

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?

like image 796
user94154 Avatar asked May 09 '10 20:05

user94154


1 Answers

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


like image 189
dbyrne Avatar answered Nov 15 '22 06:11

dbyrne