tags:

views:

233

answers:

2

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?

+6  A: 

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


dbyrne
+4  A: 

In general, "better" in programming means different things. For example, better program

  1. is easier to understand, i.e. expresses the intent better
  2. is easier to maintain. For example, less lines of code, less error-prone, etc.
  3. has better performance, in terms of execution time
  4. has better performance, in terms of memory usage

etc.

Since we are talking about Ruby, the performance is typically of a lesser concern. If you really need performance, you might consider another programming language. So, I would look at criteria (1) and (2) first. The better looking Ruby code usually represents a "better" program. Which code looks better? Which expresses the intent better? Which would be easier to modify if you add/remove logic? It depends on your problem, and it's a matter of taste, to certain degree.

To me, in your short example, the hash solution is better. The case solution provides more flexibility, which you don't need in this case (but might need in other cases).

Igor Krivokon