Refactoring2-1

基本動作の確認

グラフを表示するsvgを取り上げている.rubyスクリプトを次のようにして実行すると,何をしたいかはわかる.wcとtailはsafari等での表示ができるように,頭の3行を削る常套手段.

[bob-no-MacBook-Pro:Ruby/rrwb/lecture] bob% ruby 1.1.rb > 1.1.txt
[bob-no-MacBook-Pro:Ruby/rrwb/lecture] bob% wc 1.1.txt
      17    1044    8040 1.1.txt
[bob-no-MacBook-Pro:Ruby/rrwb/lecture] bob% tail -14 1.1.txt > 1.1.svg
[bob-no-MacBook-Pro:Ruby/rrwb/lecture] bob% open -a safari 1.1.svg

NUMBER_OF_TOSSES = 1000
BORDER_WIDTH = 50

def toss
  2 * (rand(2)*2 - 1)
end

def values(n)
  a = [0]
  n.times { a << (toss + a[-1]) }
  a
end

def spark(centre_x, centre_y, value)
  "<rect x=\"#{centre_x-2}\" y=\"#{centre_y-2}\"
    width=\"4\" height=\"4\"
    fill=\"red\" stroke=\"none\" stroke-width=\"0\" />
  <text x=\"#{centre_x+6}\" y=\"#{centre_y+4}\"
    font-family=\"Verdana\" font-size=\"9\"
    fill=\"red\" >#{value}</text>"
end

$tosses = values(NUMBER_OF_TOSSES)
points = []
$tosses.each_index { |i| points << "#{i},#{200-$tosses[i]}" }

data = "<svg xmlns=\"http://www.w3.org/2000/svg\"
     xmlns:xlink=\"http://www.w3.org/1999/xlink\" >
  <!-- x-axis -->
  <line x1=\"0\" y1=\"200\" x2=\"#{NUMBER_OF_TOSSES}\" y2=\"200\"
            stroke=\"#999\" stroke-width=\"1\" />
  <polyline fill=\"none\" stroke=\"#333\" stroke-width=\"1\"
    points = \"#{points.join(' ')}\" />
  #{spark(NUMBER_OF_TOSSES-1, 200-$tosses[-1], $tosses[-1])}
</svg>"

puts "Content-Type: image/svg+xml
Content-Length: #{data.length}

#{data}"
Content-Type: image/svg+xml
Content-Length: 8364

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink" >
  <!-- x-axis -->
  <line x1="0" y1="200" x2="1000" y2="200"
            stroke="#999" stroke-width="1" />
  <polyline fill="none" stroke="#333" stroke-width="1"
    points = "0,200 1,198 2,200 3,202 4,200 5,198 6,196 7,194 8,192 9,194 10,196 11,194 12,192 13,194 14,196 15>,198 16,200 17,198 18,200 19,202 1000,204" />
  <rect x="997" y="202"
    width="4" height="4"
    fill="red" stroke="none" stroke-width="0" />
  <text x="1005" y="208"
    font-family="Verdana" font-size="9"
    fill="red" >-4</text>
</svg>
Last modified:2020/08/04 18:09:50
Keyword(s):
References:[Refactoring2] [RubyPrimary]