So I am still fairly new to ruby, though I have noticed that it is very hard to create 2d-array and that hashes seem to be more of the go to data structure than arrays.
I was wondering why the Ruby community is so focused on Hashes and maybe if there is something more ruby-idiomatic than a 2d-array when trying to create something like a game board.
2
Many times a hash can be more convenient than an array. The use of a compound key (or hash of hashes) can be used to simulate multidimensional arrays. This is of signficant use when the array would otherwise be a sparse array or a [jagged array]. Hashes can be easier for these cases, and they can be surprisingly common.
However, hashes aren’t ordered data. While it is very easy to put the data into a hash, it becomes more complicated to get it back out in an ordered way. Much more complicated than just using the appropriate array in the first place.
Another factor to consider, hashes are indeed easy. There are a number of transformations with ruby arrays that can be confusing – there are nearly twice as many methods in Array as in Hash. Thus, if you’re just tossing some data that you will want to access (and don’t care about the order), especially if it is data that isn’t related to each other, putting it in a hash is much easier conceptually.
Many times, hashes will stand in for a quick anonymous data object with some fields rather than making up an entirely new class for it (this is likely a better choice than metaprogramming an anonymous object with the fields to pass around). It is easier to remember that ‘userid’ is in the ‘userid’ key rather than element 0 of the array.
Using a hash is only idiomatic when the data doesn’t have an underlying, enumerable order to it already.
8