A way to simplify code

is there anyway to simplify this?

toolbar = toolbar.add_item(cmd)
toolbar = toolbar.add_item(cmd2)
toolbar = toolbar.add_item(cmd3)
toolbar = toolbar.add_item(cmd4)
toolbar = toolbar.add_item(cmd5)
toolbar = toolbar.add_item(cmd6)
toolbar = toolbar.add_item(cmd7)
toolbar = toolbar.add_item(cmd8)
toolbar = toolbar.add_item(cmd9)

I tried with this but didn’t work

comandos = [cmd ,cmd1, cmd2, cmd3, cmd4 ,cmd5, cmd6, cmd7, cmd8, cmd9]
comandos.each |c| { toolbar = toolbar.add_item(c) }

Also I tried to simlify this with a for loop but didn’t work

@dialog.add_action_callback("addParam1") { |action_context| insertaContenido(1, "archivo") }
@dialog.add_action_callback("addParam2") { |action_context| insertaContenido(2, "archivo") }
@dialog.add_action_callback("addParam3") { |action_context| insertaContenido(3, "archivo") }
@dialog.add_action_callback("addParam4") { |action_context| insertaContenido(4, "archivo") }
@dialog.add_action_callback("addParam5") { |action_context| insertaContenido(5, "archivo") }

I tried:

for i in (1..5)
  @dialog.add_action_callback("addParam#{i.to_s}") { |action_context| insertaContenido(i, "archivo") }

Edit it to
comandos.each |c| { toolbar.add_item(c) }
it should work, but remember that you need to set up the toolbar definition earlier in your code…
do not use toolbar = toolbar.add_item() because you are then resetting toolbar after the first iteration…

Thanks @TIG . That was the problem, all commands was reset and all of them run as the last iteration.
The toolbar is set up at the beginning.

Normally the |c| needs to be within the block ? Ie …

comandos.each { |c| toolbar.add_item(c) }
1 Like

Why not just pass the integer from Javascript to a single Ruby callback …

  @dialog.add_action_callback("get_param") { |_ac, param|
    insertaContenido(param, "archivo")


Thanks @TIG and @DanRathbun.
All of your tips worked like charm. You are better than IA!!