如何在Ruby哈希中动态设置嵌套键的值

问题描述:

应该很容易,但是我找不到合适的解决方案. 对于第一级按键:

it should be easy, but I couldn't find a proper solution. for the first level keys:

resource.public_send("#{key}=", value)

但是对于foo.bar.lolo吗?

我知道我可以像下面这样:

I know that I can get it like the following:

'foo.bar.lolo'.split('.').inject(resource, :send)

resource.instance_eval("foo.bar.lolo")

但是在不知道嵌套级别的情况下如何将值设置为最后一个变量,它可能是第二或第三.

but how to set the value to the last variable assuming that I don't know the nesting level, it may be second or third.

是否有一种通用的方法可以在所有级别上做到这一点? 对于我的示例,我可以按照以下方式进行操作:

is there a general way to do that for all levels ? for my example I can do it like the following:

resource.public_send("fofo").public_send("bar").public_send("lolo=", value)

出于好奇而对哈希的答案:

Answer for hashes, just out of curiosity:

hash = { a: { b: { c: 1 } } }
def deep_set(hash, value, *keys)
  keys[0...-1].inject(hash) do |acc, h|
    acc.public_send(:[], h)
  end.public_send(:[]=, keys.last, value)
end

deep_set(hash, 42, :a, :b, :c)
#⇒ 42
hash
#⇒ { a: { b: { c: 42 } } }