Refactoring2r-8

すべてをすっ飛ばして,classを導入.

>|ruby|

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

class Sparkline

 attr_reader :y_values
 def initialize(y_values)
   @y_values = y_values
 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(length)
   "<!-- x-axis -->
 #{SVG.line(0,200,length,200,"#999","1")}"
 end
 def sparkline(tosses)
   points = []
   tosses.each_index { |i| points << "#{i},#{200-tosses[i]}" }
   "<!-- sparkline -->
 #{SVG.polyline(points,"none","#333","1")}"
 end

 def to_svg
   %Q{<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" > <!-- x-axis -->
 #{x_axis(y_values.length)}
 #{sparkline(y_values)}
 #{spark(y_values.length-1, 200-y_values[-1], y_values[-1])}
 </svg>}
 end

end

tosses = values(NUMBER_OF_TOSSES)

puts Sparkline.new(tosses).to_svg

<
Last modified:2024/04/20 20:44:26
Keyword(s):
References:[RubyPrimary]