微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 如何使用命名索引(键)数组在嵌套哈希中设置值?

给定任何嵌套哈希,例如:

{ canada: 
  { ontario: 
    { ottawa: :me},manitoba: 
    { winnipeg: nil}},united_states: 
  { district_of_coloumbia: 
    { washington: nil}}}

如何使用任何数组键[:canada,:ontario,:ottawa]或[:united_states,:district_of_columbia,:washington]来获取或设置值.

基本上,我的问题是如何将[:canada,:ottawa]更改为格式hash [:canada] [:ontario] [:ottawa]的getter或setter,当我不知道它的长度时键数组.

所以我可以这样做:

hash[:canada][:ontario][:ottawa] = nil
hash[:canada][:manitoba][:winnipeg] = :me

我使用递归制作了一个getter:

def reindex(h,index_array)
  i = index_array.shift
  result = index_array.empty? ? h[i] : reindex(h[i],index_array)
  result
end

但是我觉得我在想这个,应该有一个更简单的方法.

解决方法

更简单的方法(在我看来)是连续访问元素:[]:

keys = [:canada,:ontario,:ottawa]
hash = { canada: { ontario: { ottawa: :me},manitoba: { winnipeg: nil} },united_states: { district_of_coloumbia: { washington: nil } } }

# get
p keys.inject(hash) { |h,k| h.public_send(:[],k) }
#=> :me

# set
last = keys[0..-2].inject(hash) { |h,k) }
last.public_send(:[]=,keys[-1],'other')
p hash #=> {:canada=>{:ontario=>{:ottawa=>"other"},:manitoba=>{:winnipeg=>nil}},:united_states=>{:district_of_coloumbia=>{:washington=>nil}}}

包含在方法中:

def get_by_keys(hash,keys)
  keys.inject(hash) { |h,k) }
end

def set_by_keys(hash,keys,v)
  last = keys[0..-2].inject(hash) { |h,k) }
  last.public_send(:[]=,v)
  hash
end

keys = [:canada,united_states: { district_of_coloumbia: { washington: nil } } }

p get_by_keys(hash,keys) #=> :me
p set_by_keys(hash,'other') #=> {:canada=>{:ontario=>{:ottawa=>"other"},:united_states=>{:district_of_coloumbia=>{:washington=>nil}}}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐