From: thunk Date: 2010-02-04T09:00:12+09:00 Subject: Re: Hashes versus Arrays On Feb 3, 12:27 pm, Jerome David Sallinger wrote: > Hello, > > Can someone please explain how you would go about deciding whether to > use a Hash or and Array for a given requirement. Can someone give an > idiot proof simple explanation including any pros versus cons. > > Sal > -- > Posted viahttp://www.ruby-forum.com/. I think that the Hash container (may I use that term?) can be thought of primarily as a "Dictionary" - for (fast) random access. What is so darned "cool" about Hashes is that at any time the data can be: 1. an Array, 2 Another Hash and so on.... until you can give yourself a headache. Array are useful for "Stack" operations. I love the "pop" and "push" - reminds me of registers in a calculator. The Wee library comes with a "HP" reverse polish "calculator" implemented in 10 lines of code or so - amazing and so powerful - but not the stuff of most apps except maybe sometimes inside Hash. That's when Arrays are useful when the ORDER is all you need. If you want the last element you can fetch it and remove it with the thingyAr.pop command. This is a pretty common situation. (Think keyboard commands and such) Of course we are entirely OO in Ruby so any element can be anything - a Web component or - oh no!!! a Hash! Not sure it is "best practice" and I'm waiting to see how it works out BUT I have been edging toward fewer containers and using them for more and more. Many of my methods in my web related work return Hashes now so I can put names to the data. Using an array and trying to remember position for the same purpose would be really error prone. Hashes have some really nice features also! Like this one: myValue = someHash.fetch( :thingyAr, [] ) What's that about? if the symbol :thingyAr is not found an empty array is returned - thus you can fall right into your code to do something with the Array without testing for that annoying "nil".