1

top, top_middle, bottom_middle and bottom are four long strings.

How can I DRY up the following given that current's string values are the same as the name of the variable being used by the_line - but not its actual variable.

Is there some sort of "variable.variable_name" for what it is?

[top,top_middle,bottom_middle,bottom].each_with_index do |the_line, i|
  current=
    case i
      when 0 then "top"
      when 1 then "top_middle"
      when 2 then "bottom_middle"
      when 3 then "bottom"
    end
  puts current
  puts the_line
end

Output is okay as is:

top
 ――      |   ――    ――   |  |   ――   |      ――    ――    ―― 
top_middle
|  |     |   __|   __|  |__|  |__   |__      |  |__|  |__|
bottom_middle
|  |     |  |        |     |     |  |  |     |  |  |     |
bottom
 ――      |   ――    ――      |   ――    ――      |   ――      |
1

1 Answer 1

3

Rather than having each of those related things as separate variables, I'd put the four of them together in a Hash:

lines = {
  :top           => ' ――      |   ――    ――   |  |   ――   |      ――    ――    ―― ',
  :top_middle    => '|  |     |   __|   __|  |__|  |__   |__      |  |__|  |__|',
  :bottom_middle => '|  |     |  |        |     |     |  |  |     |  |  |     |',
  :bottom        => ' ――      |   ――    ――      |   ――    ――      |   ――      |'
}

That cleans things up nicely:

lines.each do |current, the_line|
  puts current
  puts the_line
end

This produces:

top
 ――      |   ――    ――   |  |   ――   |      ――    ――    ―― 
top_middle
|  |     |   __|   __|  |__|  |__   |__      |  |__|  |__|
bottom_middle
|  |     |  |        |     |     |  |  |     |  |  |     |
bottom
 ――      |   ――    ――      |   ――    ――      |   ――      |

(If you really need current as a string, you can call to_s on it, but leaving it as a symbol is fine in this case.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.