From: Matthew Kerwin Date: 2013-02-25T08:29:32+09:00 Subject: Re: splat operator and Ruby instance variable assignments --f46d0408da07c2625704d680cb26 Content-Type: text/plain; charset=ISO-8859-1 On 25 February 2013 02:24, Love U Ruby wrote: > when we write the "range" with splat(*) generally got the array as > below: > > >> a = *(2..5) > => [2, 3, 4, 5] > > But in the previous case why I got [2, 3, 4, 5] not [[2, 3, 4, 5]] > >> a = [*(2..5)] > => [2, 3, 4, 5] > >> > > here and there concept in Ruby.... Huuhh ;-) This is a legitimate question. As we've seen, on the splitting side (i.e. the RHS of an assignment, if any) the splat operator attempts to convert an object into an array, pretty sure it does it by calling that object's to_a method. Thus the following would be functionally identical: a = *(2..5) a = (2..5).to_a However it does more than that. The splitting side of splat can splice the splatted value into an array, for example: a = [1, *(2..3), 4] # => a = [1,2,3,4] By paring that down and removing the 1 and 4, you can see why: a = [ *(2..3) ] # => a = [2,3] It splices the splatted range into the existing (anonymous) array. If you want it to be nested inside, you have to explicitly call `(2..3).to_a` instead. --f46d0408da07c2625704d680cb26 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
On 2= 5 February 2013 02:24, Love U Ruby <lists@ruby-forum.com>= wrote:
when we write the "range" with spl= at(*) generally got the array as
below:

>> a =3D *(2..5)
=3D> [2, 3, 4, 5]

But in the previous case why I got [2, 3, 4, 5] not [[2, 3, 4, 5]]
>> a =3D [*(2..5)]
=3D> [2, 3, 4, 5]
>>

here and there concept in Ruby.... Huuhh ;-)

This is a legitimate question.

As we've seen, on th= e splitting side (i.e. the RHS of an assignment, if any) the splat operator= attempts to convert an object into an array, pretty sure it does it by cal= ling that object's to_a method.=A0 Thus the following would be function= ally identical:

=A0 a =3D *(2..5)
=A0 a =3D (2..5).to_a

However it does more than that.=A0 The splitting side of splat can splice = the splatted value into an array, for example:

=A0 a =3D = [1, *(2..3), 4]=A0 # =3D> a =3D [1,2,3,4]

By paring that down and removing the 1 and 4, you can see wh= y:

=A0 a =3D [ *(2..3) ] # =3D> a =3D [2,3]

It splices the splatted range into the existing (anonymous) arr= ay.=A0 If you want it to be nested inside, you have to explicitly call `(2.= .3).to_a` instead.
--f46d0408da07c2625704d680cb26--