From: Chad Perrin Date: 2007-03-16T10:05:40+09:00 Subject: Re: to_a On Fri, Mar 16, 2007 at 09:57:43AM +0900, Corey Konrad wrote: > > 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. I think more familiarity with object oriented programming concepts may help you sort these things out. Even though from a non-OOP background it may look like array.to_a is doing something to the array variable, it's not. The .to_a in that is a "message" you send to the object, "array". That object, then, does "to_a". It doesn't change itself -- it just uses "to_a" to give you an array version of itself. In other words, "array" doesn't "change to a", it emits "to a", which you can then capture somewhere. Think of objects, generally speaking, as immutable things that do stuff for you when you ask nicely. You can get around that with the assignment operator and bang-punctuated methods, but in general you're not changing the object. Instead, you're getting it to give you something. That's oversimplified in the extreme, and prone to error if taken too literally, but in general that's why .to_a gives you a return value rather than changing the object. Interestingly, this philosophy of OOP also overlaps somewhat with the functional programming paradigm, which is why many people think of Ruby as an excellent language as a stepping stone to more-pure functional programming languages. -- CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ] "The ability to quote is a serviceable substitute for wit." - W. Somerset Maugham