1

I am dealing with fractals. You start with a rectangle, and that shape is decreased by a given decay rate. I have it set up to do the first 10 iterations of the given scenario, and each scenario looks like this:

y_1 = dec_y(y_1)
y_2 = dec_y(y_2)
a_y = [y_1, y_2]
rect_1 = TkcRectangle.new(canvas, [0,0], a_y)

where dec_y is defined as the following:

def dec_y(y)
    to_ret = y / $rate
    return to_ret
end

I want to turn the first snippet into a function/method (not exactly sure what the Ruby term is...), so that each iteration will just be a single line referencing a method, which makes the problem more extensible. But, I need each TkcRectangle to have a different name. The way I want to set it up, each TkcRectangle will have the same name. But, if I can set the name of the object to a string passed as an argument, then I should not have a problem.

How do I define the name of an object with a given string?

2 Answers 2

2

Edit : Code has not been tested, but will give you the idea.

Instead of naming each element, you can use an array and use the index instead

rectangles_array = Array.new
for each loop
  rectangles_array << create_rectangle_object(y_1, y_2, canvas)
end for each loop

def dec_y(y)
  to_ret = y / $rate
  return to_ret
end

def create_rectangle_object(y_1, y_2, canvas)
  return TkcRectangle.new(canvas, [0,0], [dec_y(y_1), dec_y(y_2)])
end

If you really want to name it read about structs.. Something like

MyRectangleStruct = Struct.new(:obj_name, :x1, :y1, :x2, :y2)
puts MyRectangleStruct.new(:obj_name => 'First_rec', .....)
Sign up to request clarification or add additional context in comments.

3 Comments

Can you please explain what exactly the for loop is doing?
As you start to solve the next problem, I doubt that you will need to name your objects. The index should be sufficient. Sorry, if I misunderstood your question.
No, I think I get it... I should be able to get this to work, thank you :)
0
define_method(method_name, &block)

with method_name being any string and &block being a block of ruby code; usually it looks something like this:

define_method(method_name) do
  your code goes here
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.