Alex Gutteridge
3/16/2007 1:10:00 AM
On 16 Mar 2007, at 09:57, Corey Konrad wrote:
> Alex Gutteridge wrote:
[snip!]
> 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?
Not quite. It's converting the Range to an Array and giving it to
you, but you don't tell it to do anything with the new Array.
array = array.to_a
is what you're missing here. Almost all standard Ruby methods work
this way unless you see one with a '!' in the method name. They are
'non-destructive', so they don't effect the object you call them on.
Instead, they give you a new object. For example, the 'compact' and
compact!' methods in the Array class both remove nil elements from an
Array, but they work slightly differently. Compare:
arr = [1,nil,2,3]
arr.compact
puts arr[1]
with
arr = [1,nil,2,3]
arr.compact!
puts arr[1]
Alex Gutteridge
Bioinformatics Center
Kyoto University