On Mar 15, 8:33 pm, Corey Konrad <0... / hush.com> 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 viahttp://www.ruby-forum.com/.

You're getting closer.  It's correct that #to_a does not transform the
range into an array.  In Ruby, methods that change the object they're
called on are usually marked with a !, like #sort! on Array (sorts the
array in place) or #capitalize! on String (uppercases the first letter
in place).  Otherwise you can usually expect to get a new object back.

Here's a snippet that uses () to build the array but still doesn't
work:

array = (1..8)    # Create a Range object, give it the name "array"
array.to_a        # Call the method "to_a" on the Range, get back an
Array, but
                  # don't put it anywhere
puts array[1]     # Message not understood, because "array" is the
original Range.

It just occurred to me that you might also be confused about what's
happening in the
first line of your working example.

array = (1..8).to_a

The assignment to "array" is done _last_.  So this reads as "Create a
new Range from 1 to 8, send it the message 'to_a', then store the
result of all of that in 'array'", not "Create a new Range from 1 to
8, store that in 'array', then send it the message 'to_a'".

Just out of curiosity, is this your first programming language, or if
not what is your background?  The issues you're encountering are
things that you'll run into in many languages, Ruby just isn't quite
as verbose in having them :-)