From: "Brett H. Williams" Date: 2003-06-06T13:22:00+09:00 Subject: Re: Array = Hash.sort ... but sometimes not On Jun 6, Anubis wrote: > (sorry for my poor English : I'm French) > > I created a little program in Ruby as an exercice to learn more about this > fascinating language. > The problem is that I can change the type of one of my variables without any > problem for Ruby. > A few lines from my program : > > mots_tries = Array.new > mots_occur = Hash.new > > # I fill my Hash with some data and after that I sort it by values : > mots_tries = mots_occur.sort {|a,b| a[1]<=>b[1]} > > My program works perfectly, ... even when I declare mots_tries as an Hash : > mots_tries = Hash.new When you say: mots_tries = Array.new you are assigning the variable mots_tries to be a new empty Array. When you say: mots_tries = mots_occur.sort {|a,b| a[1]<=>b[1]} you are reassigning the variable to be result of the method sort. When you do this, the old empty Array no longer has any references to it, and it eventually will be garbage collected. Basically, there is no reason to indicate that mots_tries = Array.new in this case, as you then reassign it immediately to something else. The same thing happens when you assign it to Hash.new... the next call reassigns the variable and the empty hash is 'lost'. Variables in Ruby can point to objects of any type. Objects are typed, but not variables. Does that make sense? This is the way Ruby works, it is not a problem. For example, this program is all completely legal: foo = "a" puts foo.type # this will be String foo = 1 puts foo.type # this will be Fixnum foo = 16.1 puts foo.type # this will be Float foo = File.new("temp") puts foo.type # this will be File HTH, Brett