1

toptop_middlebottom_middleおよびbottomは 4 つの長い文字列です。

currentの文字列値が - で使用されている変数の名前と同じであるがthe_line、実際の変数ではない場合、次をどのように DRY できますか。

それが何であるかについて、ある種の「variable.variable_name」はありますか?

[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

出力はそのままで問題ありません:

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

1 に答える 1

3

これらの関連するものを個別の変数として持つのではなく、4 つを Hash にまとめます。

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

それは物事をきれいに片付けます:

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

これにより、次が生成されます。

上
 ―― | ―― ―― | | | ―― | ―― ―― ――
上中
| | | | | | __| __| |__| |__ |__ | |__| |__|
下中央
| | | | | | | | | | | | | | | | | | | | | | | | | |
下
 ―― | ―― ―― | ―― ―― | ―― |

(文字列として本当に必要な場合は、それcurrentを呼び出すことができますがto_s、この場合はシンボルとして残しても問題ありません。)

于 2013-06-15T21:25:45.857 に答える