Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Assigning Ruby Variables with a Case Statement

Reading Refactoring: Ruby Edition I came across an example of assigning a variable via a case statement. For example:

Code

#!/usr/bin/env ruby

trigger_value = 7

output_string = case trigger_value
  when 1
    "First number"
  when 7
    "Lucky number"
  else
    "Something else"
end

puts output_string   # Outputs: Lucky number

Using the return values from the case statement directly for the assignment is much cleaner than the way I used to do it:

Code

#!/usr/bin/env ruby

trigger_value = 7
output_string = ""

case trigger_value
  when 1
    output_string = "First number"
  when 7
    output_string = "Lucky number"
  else
    output_string = "Something else"
end

puts output_string   # Outputs: Lucky number

I'm learning that most case statements are prime candidates for refactoring. The direct assignment is a nice way to use them until that happens.