From: Marnen Laibow-Koser Date: 2010-02-04T12:44:14+09:00 Subject: Re: Hashes versus Arrays thunk wrote: > 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. So can an Array. The only difference is that array indices have to be numeric. > 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. The same is true of arrays. > > Array are useful for "Stack" operations. But that's not really their primary purpose. > 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. Uh, what? That last phrase appears not to make sense. > 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) Right, although you'd probably want a more sophisticated Stack object... > > Of course we are entirely OO in Ruby so any element can be anything - > a Web component or - oh no!!! a Hash! Right. Or anything else. > > 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. If you want to put names to the data, you should be using value objects, not hashes. > Using an array and trying to remember > position for the same purpose would be really error prone. > Yup. And using a Hash is also error-prone. Define a custom value object. > 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". Pretty useless, considering that you can use || for the same thing BTW, camelCase is considered poor style in Ruby; use underscore_case instead. Best, --  Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.