简体   繁体   中英

ruby hash of arrays that contain arrays

I'm learning ruby and am having some trouble working with hashes that contain multi-dimensional arrays.

For example, I'm trying to create a hash with keys that are a city names. Then, inside that city, I want to have an array that contains arrays of data.

It should look something like this:

hash = {"chicago" => [["carl","blue"], ["ross", "red"]], "new york" => [ ["linda", "green"], ["john", "purple"], ["chris", "black"]]}

How can I make this work, and how can I access/append to the arrays inside of each key?

I've been trying something like:

hash["chicago"][].push["new person", "color"]

Thanks, I know this is pretty trivial, but I can't seem to wrap my head around in it Ruby.

It's helpful to break things down into steps. So, we know hash is the hash, and hash['chicago'] is the array of arrays, so from this we can see that we want to push into hash['chicago'] . This means that the only thing wrong with your code is that you have an extra pair of braces. So we get:

hash['chicago'].push ['new person', 'yellow or something']

In these cases, I typically define the hash with a default proc that determines what should happen when a given key is not present in the hash:

hash = Hash.new {|h,k| h[k] = [] }

In this case, the default value is an empty array. Adding new data to the hash is then as simple as:

hash["chicago"] << ["carl", "blue"]

One caveat - if you're doing lookups, missing values will be represented as an empty array. You can work around this using fetch rather than the square bracket notation:

hash.fetch("chicago", nil) #=> [["carl", "blue"]]
hash.fetch("new york", nil) #=> nil

Here is a way :

hash = Hash.new { |h,k| h[k] = [] }
hash["chicago"].push ["carl","blue"]
hash["chicago"].push ["ross", "red"]
hash
# => {"chicago"=>[["carl", "blue"], ["ross", "red"]]}

hash["new york"].push ["linda", "green"]
hash["new york"].push ["john", "purple"]

hash
# => {"chicago"=>[["carl", "blue"], ["ross", "red"]],
#     "new york"=>[["linda", "green"], ["john", "purple"]]}

From new {|hash, key| block } → new_hash new {|hash, key| block } → new_hash

If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block's responsibility to store the value in the hash if required.


how can I access ?

Use Hash#fetch or Hash#[] for the same, which suits your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM