使用键数组遍历嵌套的Ruby哈希

时间:2016-11-19 04:24:36

标签: arrays ruby hashtable

给定具有n级嵌套值的哈希值,字段名称和路径

def get_value(hash, field, path)
  ?
end

get_value(contact, "Record", ["Account", "Team"])
=> 1234

如何定义一个方法来检索路径末尾的字段值。

#executor

3 个答案:

答案 0 :(得分:4)

您可以使用new_request = RequestFactory().post('/settings/', next_request) new_request.session = request.session user = User.objects.get(username=username) user.backend = 'django.contrib.auth.backends.ModelBackend' login(new_request, user) new_request.user = user return views.client_form(new_request) :表示Array#inject,然后hash['Account']['Team']

return_value_of_inject['Record']

BTW,def get_value(hash, field, path) path.inject(hash) { |hash, x| hash[x] }[field] end get_value(contact, field, path) # => 1234 怎么样?

get_value(contact, ['Account', 'Team', 'Record'])

def get_value2(hash, path) path.inject(hash) { |hash, x| hash[x] } end get_value2(contact, ['Account', 'Team', 'Record']) # => 1234

get_value(contact, 'Account.Team.Record')

答案 1 :(得分:4)

让我们来看看"字段"作为"路径"的最后一个元素。然后就是

def grab_it(h, path)
  h.dig(*path)
end

grab_it contact, ["Account", "Team", "Record"]
  #=> 1234 
grab_it contact, ["Account", "Team", "Rabbit"]
  #=> nil
grab_it(contact, ["Account", "Team"]
  # => {"Closing_Sales"=>"Bob Troy", "Record"=>1234} 
grab_it contact, ["Account"]
  #=> {"Exchange"=>true, "Gmail"=>false, "Team"=>{"Closing_Sales"=>"Bob Troy",
  #    "Record"=>1234}} 
在v2.3中添加了

Hash#dig

答案 2 :(得分:1)

def get_value(contact, field, path)
  path.inject(contact) {|p, j| p.fetch(j, {}) }.fetch(field, nil)
end