What does a * in front of a string literal do in ruby?
Asked Answered
E

3

5

This code seems to create an array with a range from a to z but I don't understand what the * does. Can someone please explain?

[*"a".."z"]
Expediency answered 27/10, 2010 at 8:9 Comment(1)
In this case, it's not in front of a string literal, it's in front of a Range.Decentralize
S
12

It's called splat operator.

Splatting an Lvalue

A maximum of one lvalue may be splatted in which case it is assigned an Array consisting of the remaining rvalues that lack corresponding lvalues. If the rightmost lvalue is splatted then it consumes all rvalues which have not already been paired with lvalues. If a splatted lvalue is followed by other lvalues, it consumes as many rvalues as possible while still allowing the following lvalues to receive their rvalues.

*a = 1
a #=> [1]

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

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

Empty Splat

An lvalue may consist of a sole asterisk (U+002A) without any associated identifier. It behaves as described above, but instead of assigning the corresponding rvalues to the splatted lvalue, it discards them.

a, *, b = *(1..5)
a #=> 1
b #=> 5

Splatting an Rvalue

When an rvalue is splatted it is converted to an Array with Kernel.Array(), the elements of which become rvalues in their own right.

a, b = *1
a #=> 1
b #=> nil

a, b = *[1, 2]
a #=> 1
b #=> 2

a, b, c = *(1..2), 3
a #=> 1
b #=> 2
c #=> 3
Shizukoshizuoka answered 27/10, 2010 at 8:16 Comment(1)
Aside from assigning values, you can also use the splat operator in defining methods: def do_it(arg1, *args). Now you can call do_it(1, 2) and do_it(1, 2, 3, 4).Sauceda
C
0

The splat operator expands the range into an array.

Contribution answered 27/10, 2010 at 8:23 Comment(1)
In some cases*, this is true. :)Apterous
A
0

Huh, fun fact. When you do this:

*(0..50)

you get an error.

The splat operator, in this case, requires a receiver in order to work. So don't fool yourself into thinking its broken in irb by just trying it without a receiver.

Apterous answered 26/9, 2012 at 3:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.