On Tue, Mar 9, 2010 at 10:35 PM, Dhananjay B. <
[email protected]> wrote:
Your question is ambiguous, but I’ll assume it is in regards to the
ordering. A hash table is a data structure intended to give you fast
(near
constant time) access to your elements. It is based off of key/value
pairs.
So you put in a key/value pair, and later, you can get the value out by
submitting the key.
It does this by deriving a number from the object’s state, to determine
the
(probable) location of the object in an array that it keeps internally,
then
looking ot see if it is there.
Because these numbers are not guaranteed to be in the same sequence you
submitted them, the ordering within the array is not guaranteed.
So when you say hash.each, it is more interested in making sure that you
see
each of the elements in the hash, than it is in making sure you see them
in
the same order you submitted them. In this way, it is more like a set
than
an ordered list.
So you should think about the manner in which you are using the objects,
and
decide if a hash is really the data structure you are wanting. Based on
your
use, an array may better fit your needs.
array_fruit = Array.new
array_fruit << [‘mango’ ,‘orange’]
array_fruit << [‘banana’,‘yellow’]
array_fruit << [‘grapes’,‘green’ ]
array_fruit << [‘apple’ ,‘red’ ]
array_fruit.each do |key,value|
puts “#{key} #{value}”
end
or
array_fruit = [ [‘mango’,‘orange’] , [‘banana’,‘yellow’] ,
[‘grapes’,‘green’] , [‘apple’,‘red’] ]
array_fruit.each do |key,value|
puts “#{key} #{value}”
end
or
array_fruit = [ %w(mango orange) , %w(banana yellow) , %w(grapes green)
,
%w(apple red) ]
array_fruit.each do |key,value|
puts “#{key} #{value}”
end
Also notice that if you switch to 1.9, then they will be ordered in the
manner in which they were added. Hashes in Ruby 1.9 preserve insertion
order. (
http://img163.imageshack.us/img163/1726/picture1hrm.png