The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Assigning Ruby Variables with a Case Statement

TODO: Pull subtitle into page object

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

code_start_default_section code_end_default_section

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.

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Assigning Ruby Variables with a Case Statement

-- p

Reading <<link|Refactoring: Ruby Edition|http://smile.amazon.com/dp/0321984137>> I came across an example of assigning a variable via a case statement. For example:

-- code/
-- ruby{numberLines: true}

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

-- /code

-- p

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

-- code/
-- ruby{numberLines: true}

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

-- /code

-- p

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.


-- categories
-- Ruby

-- metadata
-- date: 2014-11-08 00:00:00
-- id: 20en0nhd
-- status: published
-- type: post
-- SCRUBBED_NEO: false
-- site: aws