Refactoring2-6

名は体を表す

何をしているかが分かるように,spark, sparkline, x-axisという関数に換える. ついでにtosses関係をいじる.

>|ruby| refact後 require 'svg0.rb' NUMBER_OF_TOSSES = 20

def toss

 2 * (rand(2)*2 - 1)

end

def values(n)

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

end

SQ=4 SPARK_COLOR='red' def spark(cx, cy, value)

 "<!-- spark -->
 #{SVG.rect(cx-SQ/2,cy-SQ/2,SQ,SQ,'red','none',0)}
 #{SVG.text(cx+6, cy+4, value,"Verdana","9",SPARK_COLOR)}"

end def x_axis(points)

 "<!-- x-axis -->
 #{SVG.line(0,200,NUMBER_OF_TOSSES,200,"#999","1")}"

end def sparkline(points)

 "<!-- sparkline -->
 #{SVG.polyline(points,"none","#333","1")}"

end

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

data = %Q{<svg xmlns="http://www.w3.org/2000/svg"

    xmlns:xlink="http://www.w3.org/1999/xlink" > <!-- x-axis -->
 #{x_axis(points)}
 #{sparkline(points)}
 #{spark(tosses.length-1, 200-tosses[-1], tosses[-1])}

</svg>}

puts data

<
Last modified:2024/04/27 09:51:48
Keyword(s):
References:[Refactoring2] [RubyPrimary]