ruby 使用Hash#dig或Lonely运算符(&.)将值安全地分配给嵌套哈希,

3vpjnl9f  于 2023-03-12  发布在  Ruby
关注(0)|答案(7)|浏览(122)
h = {
  data: {
    user: {
      value: "John Doe" 
    }
  }
}

要给嵌套哈希赋值,我们可以使用

h[:data][:user][:value] = "Bob"

然而,如果中间的任何部分缺失,则会导致错误。
就像

h.dig(:data, :user, :value) = "Bob"

无法工作,因为还没有Hash#dig=可用。
为了安全地赋值,我们可以

h.dig(:data, :user)&.[]=(:value, "Bob")    # or equivalently
h.dig(:data, :user)&.store(:value, "Bob")

但有没有更好的办法呢?

lf5gs5x2

lf5gs5x21#

它不是没有警告(如果您从其他地方接收哈希值,它就不起作用),但一个常见的解决方案是:

hash = Hash.new {|h,k| h[k] = h.class.new(&h.default_proc) }

hash[:data][:user][:value] = "Bob"
p hash
# => { :data => { :user => { :value => "Bob" } } }
jaxagkaj

jaxagkaj2#

基于@rellampec的答案,我们可以找到不抛出错误的方法:

def dig_set(obj, keys, value)
  key = keys.first
  if keys.length == 1
    obj[key] = value
  else
    obj[key] = {} unless obj[key]
    dig_set(obj[key], keys.slice(1..-1), value)
  end
end

obj = {d: 'hey'}
dig_set(obj, [:a, :b, :c], 'val')
obj #=> {d: 'hey', a: {b: {c: 'val'}}}
t3irkdon

t3irkdon3#

有趣的是:

def dig_set(obj, keys, value)
  if keys.length == 1
    obj[keys.first] = value
  else
    dig_set(obj[keys.first], keys.slice(1..-1), value)
  end
end

如果没有[][]=方法,无论如何都会引发异常。

sqserrrh

sqserrrh4#

我发现了一个简单的解决方案来设置嵌套哈希的值,即使父键丢失,即使哈希已经存在。

x = { gojira: { guitar: { joe: 'charvel' } } }

假设您希望包含mario's drum以生成:

x = { gojira: { guitar: { joe: 'charvel' }, drum: { mario: 'tama' } } }

最后我给猴子打了补丁Hash:

class Hash

    # ensures nested hash from keys, and sets final key to value
    # keys: Array of Symbol|String
    # value: any
    def nested_set(keys, value)
      raise "DEBUG: nested_set keys must be an Array" unless keys.is_a?(Array)

      final_key = keys.pop
      return unless valid_key?(final_key)
      position = self
      for key in keys
        return unless valid_key?(key)
        position[key] = {} unless position[key].is_a?(Hash)
        position = position[key]
      end
      position[final_key] = value
    end

    private

      # returns true if key is valid
      def valid_key?(key)
        return true if key.is_a?(Symbol) || key.is_a?(String)
        raise "DEBUG: nested_set invalid key: #{key} (#{key.class})"
      end
end

用法:

x.nested_set([:instrument, :drum, :mario], 'tama')

示例的用法:

h.nested_set([:data, :user, :value], 'Bob')

我错过了什么警告?有没有更好的方法在不牺牲可读性的情况下编写代码?

vhipe2zx

vhipe2zx5#

在寻找一个类似问题的答案时,我偶然发现了一个类似于@niels-kristian答案的接口,但我还想支持一个名称空间定义参数,比如xpath。

def deep_merge(memo, source)
  # From: http://www.ruby-forum.com/topic/142809
  # Author: Stefan Rusterholz
  merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
  memo.merge!(source, &merger)
end

# Like Hash#dig, but for setting a value at an xpath
def bury(memo, xpath, value, delimiter=%r{\.})
  xpath = xpath.split(delimiter) if xpath.respond_to?(:split)
  xpath.map!{|x|x.to_s.to_sym}.push(value)
  deep_merge(memo, xpath.reverse.inject { |memo, field| {field.to_sym => memo} })
end

嵌套哈希有点像xpath,而dig的对立面是bury

irb(main):014:0> memo = {:test=>"value"}
=> {:test=>"value"}
irb(main):015:0> bury(memo, 'test.this.long.path', 'value')
=> {:test=>{:this=>{:long=>{:path=>"value"}}}}
irb(main):016:0> bury(memo, [:test, 'this', 2, 4.0], 'value')
=> {:test=>{:this=>{:long=>{:path=>"value"}, :"2"=>{:"4.0"=>"value"}}}}
irb(main):017:0> bury(memo, 'test.this.long.path.even.longer', 'value')
=> {:test=>{:this=>{:long=>{:path=>{:even=>{:longer=>"value"}}}, :"2"=>{:"4.0"=>"value"}}}}
irb(main):018:0> bury(memo, 'test.this.long.other.even.longer', 'other')
=> {:test=>{:this=>{:long=>{:path=>{:even=>{:longer=>"value"}}, :other=>{:even=>{:longer=>"other"}}}, :"2"=>{:"4.0"=>"value"}}}}
oymdgrw7

oymdgrw76#

@niels-kristian答案的一个更像ruby助手的版本
您可以像这样使用它:

a = {}
a.bury!([:a, :b], "foo")
a # => {:a => { :b => "foo" }}
class Hash
  def bury!(keys, value)
    key = keys.first
    if keys.length == 1
      self[key] = value
    else
      self[key] = {} unless self[key]
      self[key].bury!(keys.slice(1..-1), value)
    end
    self
  end
end
w6lpcovy

w6lpcovy7#

可以使用merge!

[37] pry(main)> h = {
  data: {
    user: {
      value: "John Doe"
    }
  }
=> {:data=>{:user=>{:value=>"John Doe"}}}
[38] pry(main)> h.merge!(data: {user: {value: "John Foo"}})
=> {:data=>{:user=>{:value=>"John Foo"}}}
[39] pry(main)> h
=> {:data=>{:user=>{:value=>"John Foo"}}}
[40] pry(main)> h.merge!(data: nil)
=> {:data=>nil}
[41] pry(main)> h
=> {:data=>nil}
[42] pry(main)> h.merge!(data: {user: {value: "John Foo2"}})
=> {:data=>{:user=>{:value=>"John Foo2"}}}

相关问题