Ruby Sample code of 2d Hash set

7/22/2017 posted in  编程 comments

In fact, this can be a n dimension hash set code sample, actually I create a 3-d hash to construct some kind of data structure for API rendering, it's not so beautiful, but easy to work, and not cost so much.

first_hash_key = ["A", "B", "C", "D"]
second_hash_key = ['a', "b", "c", "d"]
hash = Hash.new
first_hash_key.each do |key|
  hash[key] = Hash.new
end
p hash

# {"A"=>{}, "B"=>{}, "C"=>{}, "D"=>{}}

first_hash_key.each do |key|
  second_hash_key.each do |k|
    if hash[key][k].nil?
      hash[key][k] = 1
      # p hash["A"][k]
    else
      hash[key][k] += 1
    end
  end
end
p hash
# {"A"=>{"a"=>1, "b"=>1, "c"=>1, "d"=>1}, "B"=>{"a"=>1, "b"=>1, "c"=>1, "d"=>1}, 
# "C"=>{"a"=>1, "b"=>1, "c"=>1, "d"=>1}, "D"=>{"a"=>1, "b"=>1, "c"=>1, "d"=>1}}