I am a Perl person and I have made Hashes like this for a while:
my %date; #Assume the scalars are called with 'my' earlier $date{$month}{$day}{$hours}{$min}{$sec}++
Now I am learning Ruby and I have so far found that using this tree is the way to do many keys and a value. Is there any way to use the simple format that I use with Perl using one line?
@date = { month => { day => { hours => { min => { sec => 1 } } } } }
Nested Hashes The hashes that you've seen so far have single key/value pairs. However, just like arrays, they can be nested, or multidimensional. Nested hashes are a very common way to store complex associated data.
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
Advertisements. A Hash is a collection of key-value pairs like this: "employee" = > "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.
Unfortunately, there is no simple, practical way. A Ruby equivalent would be an ugly, ugly beast like:
((((@date[month] ||= {})[day] ||= {})[hours] ||= {})[min] ||= {})[sec] = 1
There is a way to assign default values for missing keys in hashes, though:
@date = Hash.new { |hash, key| hash[key] = {} } # @date[:month] is set to a new, empty hash because the key is missing. @date[:month][:day] = 1
Unfortunately this does not work recursively.
...unless you create it yourself; hooray for Ruby!
class Hash def self.recursive new { |hash, key| hash[key] = recursive } end end @date = Hash.recursive @date[month][day][hours][min][sec] = 1 # @date now equals {month=>{day=>{hours=>{min=>{sec=>1}}}}}
Keep in mind, though, that all unset values are now {}
rather than nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With