Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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 :

#!/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 :

#!/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.