[fxruby-users] How to iterate an array within an event

Lyle Johnson lyle at lylejohnson.name
Tue Jan 6 12:38:04 EST 2009

On Mon, Jan 5, 2009 at 6:44 PM, chen li <chen_li3 at yahoo.com> wrote:

> I have an array and here is what I try to accomplish:
> click the @button_next,assign the first element to the radioButton of @radio
> click the @button_next again, assign the second element to the same radioButton (overwrite the text or update the text)
> and so on, untill all the elements are iterated.
> I write the codes as follows. But when I run it I only see the last element 5 on the @radio. I wonder someone can
> explain to me what is going on and help me fix it.


Your loop over the array elements is currently written this way:

    @array.each do |e|
      @button_next.connect(SEL_COMMAND) do

This is equivalent to (for example):

    @button_next.connect(SEL_COMMAND) { @radio.text = "#{@array[0]}" }
    @button_next.connect(SEL_COMMAND) { @radio.text = "#{@array[1]}" }
    @button_next.connect(SEL_COMMAND) { @radio.text = "#{@array[2]}" }
    @button_next.connect(SEL_COMMAND) { @radio.text = "#{@array[3]}" }
    @button_next.connect(SEL_COMMAND) { @radio.text = "#{@array[4]}" }

Do you see now why clicking @button_next just changes the radio
button's text to "5"? Every time you call @button_next.connect(),
you've overwriting the previous block that you had associated with
that event.

You need to do something to keep track of what the current value of
the radio button is, and increment that value each time @button_next
is clicked. For this particular example, the following code ought to

    @current_index = 0
    @radio.text = "#{@array[@current_index}"
    @button_next.connect(SEL_COMMAND) do
      @current_index = @current_index + 1
      @current_index = 0 if @current_index >= @array.length
      @radio.text = "#{@array[@current_index}"

I'm guessing your real code has a more complicated data structure, but
this is the idea.

Hope this helps,


More information about the fxruby-users mailing list