Dynamically create buttons

I am a beginner and I would like to create a loop that dynamically
creates a number of normal buttons. ‘Button1’, ‘Button2’ etc.

Then I would like to be able to reference the dynamically created
buttons by typing ‘Button1’, ‘Button2’ etc

I would be very thankful if someone could help me out with this code
snippet.

Thank you

Am Sonntag, den 30.09.2007, 18:07 +0200 schrieb tobbyd dubbyd:

I am a beginner and I would like to create a loop that dynamically
creates a number of normal buttons. ‘Button1’, ‘Button2’ etc.

Then I would like to be able to reference the dynamically created
buttons by typing ‘Button1’, ‘Button2’ etc

Hi,

something like this?

@buttons = {}
10.times do |i|
@buttons[“button#{i}”] Gtk::Button.new(“button #{i}”)
end

Cheers
detlef

I think you forgot a = there detlef :slight_smile:

@buttons[“button#{i}”] = Gtk::Button.new(“button #{i}”)

Marc H. wrote:

I think you forgot a = there detlef :slight_smile:

@buttons[“button#{i}”] = Gtk::Button.new(“button #{i}”)

Fantastic work! It runs perfectly. I am a bit unsure of exactly what is
happening here, what is -> @buttons = {}
Is it some sort of array that all the buttons are stored in?

Thanks alot

tobbyd dubbyd wrote:

… I am a bit unsure of exactly what is
happening here, what is → @buttons = {}
Is it some sort of array that all the buttons are stored in?

Yes, it’s called a Hash, and it’s much more than an array.
You can learn about them here:

http://www.rubycentral.com/pickaxe/tut_containers.html
http://www.rubycentral.com/pickaxe/ref_c_hash.html

martin

tobbyd dubbyd wrote:

Fantastic work! It runs perfectly. I am a bit unsure of exactly what is
happening here, what is -> @buttons = {}

@buttons = {}
is the shortcut to
@buttons = Hash.new

This works also for arrays
a = []
does the same as
a = Array.new