From: Corey Konrad <0011@...> Date: 2007-03-16T09:57:43+09:00 Subject: Re: to_a Alex Gutteridge wrote: > On 16 Mar 2007, at 09:33, Corey Konrad wrote: > >>> The issue isn't with the parentheses, but with the behavior of the >>> >> 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 ok, yeah now i understand why the () are there i just didnt see that for some reason. See when i tried > array = 1..8 > array.to_a > puts array[1] my view was that i was creating a range and assigning it to array and then taking that range in array and converting it to an array by using array.to_a. I had no idea i was just creating a new array there is no way to tell that from looking at it for me even now, to me that code looks like i am transforming the range stored in array... into an array. My view was that array.to_a meant, take the range stored in array and convert it to an array but that isnt what its doing its just converting the variable array into an empty array? I dont know i still feel like i am missing something that is going on behind the scenes, learning ruby as a first programming language kind of seems like learning short hand english first instead of becoming fluent in english grammer. -- Posted via http://www.ruby-forum.com/.