Some notes:
Use tabspace=2.
Don't use global variables. When programming you should use functions in the same sense than you do in maths. That's a real function:
f(x, y) = x + y
, note that it takes arguments and returns some output (no globals, no states, no updates to variables outside the function).Ruby is a OOP language, so we usually define a class (or module) to contain our code.
Don't overuse statements, use expressions. This code uses statements:
x = []; x << 1; x << 2
, this one uses expressions:x = [1, 2]
.You are writing a loop where the output is the input of the next iteration. That can be written with
Enumerable#inject
(this method is somewhat difficult to grasp at first, study the docs carefully).
A more idiomatic Ruby approach would be:
require 'tk'
class Example
def initialize(options = {})
@rate = options[:rate] || 1.5
@start_point = options[:start_point] || [750, 750]
@canvas_size = options[:canvas_size] || [800, 800]
end
def run
canvas = TkCanvas.new(:width => @canvas_size[0], :height => @canvas_size[1])
canvas.pack('fill' => 'both', 'expand' => true)
101.timesupto(10).inject(@start_point) do |point, index|
# get_next_point is a 1one-liner and could be written here,
# but thislet's showsshow how weto use arguments to call functions/methods.
point2 = get_next_point(point, @rate)
circle = TkcOval.new(canvas, point, point2)
circle[:fill] = (index % 2) == 0 ? "blue""red" : "red""blue"
point2
end
Tk.mainloop
end
def get_next_point(point, rate)
[point[0] / rate, point[1] / rate]
end
end
if __FILE__ == $0
example = Example.new(:rate => 1.5, :start_point => [750, 750])
example.run
end