On 16 Mar 2007, at 09:33, Corey Konrad wrote:

> Ash wrote:
>> On Mar 15, 8:07 pm, Corey Konrad <0... / hush.com> wrote:
>>>
>>> what do the () in the above example do that makes it work?
>>>
>>> thanks
>>>
>>> --
>>> Posted viahttp://www.ruby-forum.com/.
>>
>> The issue isn't with the parentheses, but with the behavior of the
>> #to_a method.  #to_a does not modify its receiver.  Instead, it  
>> builds
>> a new instance of Array and returns it.  In the first example, you're
>> capturing the return value of #to_a and assigning it to the variable
>> "array".  In the second, you're assigning a Range to the variable
>> "array", calling #to_a on it, and tossing the Array you get back on
>> the floor.
>>
>> To make the second example work properly, you need to capture the
>> return value in a new variable and use that instead:
>>
>> array = 1..8
>> result = array.to_a
>> puts result[1]
>
> i am not sure if i understand...so to_a doesnt actually transform the
> range into an array it just creates a new array object. That still
> doesnt explain why the first one using the () works though when i  
> remove
> the () it doesnt work. I dont know this stuff is really confusing. I
> started learning ruby because i heard it was an easy and intuitive
> language but it seems pretty difficult.
>
> -- 
> Posted via http://www.ruby-forum.com/.
>

I think you understand fine, just take your time and take each step  
in turn. As you say, the code below works:

array = (1..8).to_a
puts array[1]

This makes a Range object from '(1..8)' and converts it to an Array  
using '.to_a'. This array is assigned to the variable 'array' and you  
can access it as normal.

The code below doesn't work:

array = 1..8
array.to_a
puts array[1]

This makes a Range object from '1..8' and assigns it to 'array'. You  
then create a new Array using 'array.to_a' but do not assign it to  
anything ('array' is still a Range). This means the final statement  
doesn't work.

 From your second post it looks like you tried:

array = 1..8.to_a
puts array[1]

This doesn't work because you are asking for a Range constructed from  
'1' to '8.to_a'. I.e a Range from the Integer 1 to the Array '[8]'.  
This is an invalid Range. The parentheses in the first example ensure  
that the Range is constructed first and then the '.to_a' method is  
called on that. Essentially the method call '.to_a' takes precedence  
over the Range operator '..'.

Hope that helps.

Alex Gutteridge

Bioinformatics Center
Kyoto University