Refactoring3-1

下記のコード書き換えに関する試験を受けてください.

コードの初期状態

グラフを表示するsvgを出力するコードを改良していきます.

まずは,下記コードrrwb.rbをダウンロードしてください.

NUMBER_OF_TOSSES = 10

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)
  %Q{<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 = %Q{<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink" >
  <polyline fill="none" stroke="#333" stroke-width="1"
points = "#{points.join(' ')}" />
  #{spark(NUMBER_OF_TOSSES-1, 200-$tosses[-1], $tosses[-1])}
</svg>}

puts "#{data}"

class導入[50点]

class化を行います.下のようなひな形を参考にしてSparklineクラスを作ってください.

NUMBER_OF_TOSSES = 10

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

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

class Sparkline
  def initialize
  end
    
  def spark(centre_x, centre_y, value)

  end

  def to_svg(points)
 
  end
end

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

puts Sparkline.new.to_svg(points)

class応用[50点]

$tosses(外部参照)の廃止を目指して,initializeクラスの改良,attr_readerを使ったデータ保持を行い,次のようなすっきりしたコードに書き換えてください.

NUMBER_OF_TOSSES = 10

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

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

puts Sparkline.new(values(NUMBER_OF_TOSSES)).to_svg
Last modified:2024/04/20 20:57:00
Keyword(s):
References:[RubyPrimary]