当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - writing a class that iterates over a hash of hashes

问题描述:

I'm having trouble writing a class to iterate over a hash of hashes or nested hash, here is an example of the hash I have.

 hash = {a => {:number => 1, :color => "blue", :language => english} b => {:number => 2, :color => "red", :language => english}

I want to write class methods that will return the number of each parent

网友答案:

All you need is a method, not a class. Here are a couple of approaches you could use.

def numbers(h)    
  Hash[h.map { |k,v| [k, v[:number]] }]
end

h = { :a => {:number => 1, :color => "blue", :language => "english" },
      :b => {:number => 2, :color => "red",  :language => "english" } }

numbers(h)
  #=> {:a=>1, :b=>2}

or with Ruby 2.1:

def numbers(h)    
  h.map { |k,v| [k, v[:number]] }.to_h
end

Another way that returns the same hash:

def numbers(h)    
  h.each_with_object({}) { |(k,v),g| g[k] = v[:number] }
end
分享给朋友:
您可能感兴趣的文章:
随机阅读: