Return single :key from nested hash in ruby

Deadly 提交于 2019-12-16 18:06:13

问题


From psd.rb gem by LayerVault, I get a hash that contains all the layers and groups of the psd in nested hashes. Here is a gist of the hash. I want to retrieve a certain key from that hash. Is there a way to do this and store those keys values in an array?


回答1:


def values(hsh, key)
  return [] if !hsh.kind_of? Hash
  v = hsh[key] ? [hsh[key]] : []
  hsh.values.select{|i| i.kind_of? Hash or i.kind_of? Array}.each do |val|
    if val.kind_of? Hash
      v+= values(val, key)
    else
      val.each {|i| v+= values(i, key)}
    end
  end
  return v
end

puts values(h, :blending_mode).inspect # h is the Hash from your gist
# => ["normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal"]


来源:https://stackoverflow.com/questions/17990332/return-single-key-from-nested-hash-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!