what does *my_array do?

S

Shea Martin

using tk in ruby, when I add my_array to a listbox it adds all the items
as a single large string. when I add them as *my_array it puts them in
correctly.

I got *my_array from a example on web, but I don't know what it means.

~S
 
B

Brian Palmer

It expands the array into arguments. For example:

my_array = [ "str1", "str2", "str3" ]
listbox.add(*my_array)

is the same as

listbox.add("str1", "str2", "str3")

Many Ruby APIs make it easier on the developer by automatically
expanding the array if it's the lone argument, but I guess tk
doesn't, at least not in this case.

-- Brian Palmer
 
D

David A. Black

Hi --

using tk in ruby, when I add my_array to a listbox it adds all the items as a
single large string. when I add them as *my_array it puts them in correctly.

I got *my_array from a example on web, but I don't know what it means.

It "un-arrays" the array, turning it back into a plain list of
objects. For example:

a = [3,4,5]
b = [1,2,*a] # [1,2,3,4,5]

as opposed to:

b = [1,2,a] # [1,2,[3,4,5]]

It also plays a role in method calls. This:

def x(*args)

is a method that can take any number of arguments (including zero),
and will store them in the array args.


David
 
F

Florian Groß

Shea said:
using tk in ruby, when I add my_array to a listbox it adds all the items
as a single large string. when I add them as *my_array it puts them in
correctly.

I got *my_array from a example on web, but I don't know what it means.

method(*[1, 2, 3]) is the same as method(1, 2, 3).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,812
Messages
2,569,694
Members
45,478
Latest member
dontilydondon

Latest Threads

Top