Tronic wrote:which method is more convenient to use Array or Hash?
Well, this depends very much what your data represents, and what you want to do with it.
The main differences are...
Array - just like in SM, you can only reference things by an index number, and the numbers must always be in sequence (an "ordered" array). If the things in your "collection" must always be in a certain order, with no "gaps" in the index numbers, or you might need to "count" through them, this is the one to go for.
Worth noting that, unlike in "green", the items inside the array don't all have to be the same kind; you can mix numbers, strings, graphics objects, you name it, as items in the same array.
Hash - the indexes are just 'tags' or 'names' for referring to the things in the collection - think of something like an address book; you would be unlikely to "count" through it, but you need to find a person's address by using their name to find it - an index number would be very inconvenient, especially if the index numbers changed every time you added a new friend!
But those index "keys" can be anything you like, not just 'name' strings, so there's nothing to stop you from using numbers as the "tag" names if you want - allowing you to create an array that has "gaps" in the index numbers. But if you wanted to "count" through the items, you would have to use your own code - the standard iterators (e.g. .each, 'for' loops etc.) won't keep the numbers in order for you, and you'd need to program it not to screw up if there was an "empty" index.
There's also another (small) advantage to hashes... Ruby's "object oriented" style suits them very well, and so they are slightly more efficient to look up the values than arrays - but not enough that you should use them when an array would make more sense for your application.
So to decide, ask yourself a few simple questions...
- Is a number the best thing for finding something in the collection?
- Do things need to always keep the same 'index', or do the indexes need to "shuffle up" when adding/deleting?
- Do the items need to be counted through in a predictable order?
Once that is decided, Ruby will have no problem at all doing anything you want with your data - the documentation for Arrays and Hashes shows literally dozens of commands for each one to do almost anything imaginable. So it's your data that will decide, "convenience" just isn't a problem because they are both so versatile in Ruby/
And they are so much more powerful than 'green' because they can contain absolutely any kind of object - even chunks of code to execute.
It's also not immediately obvious, but you can also do something that I always wanted inside SM - multi-dimensional (e.g. [x,y]) arrays. To do that, you make an array where each item inside is also an array - and so on, for as many layers as you like.