2

我有以下数组

["key", "key_deeper", "key_even_deeper"]

和一个哈希:

{ "key" => { "key_deeper" => { "key_even_deeper" => "BINGO!" } } }

将数组应用于要接收的哈希的最短或最具表现力的方法是"BINGO!"什么?


这是基本情况,但也有一种特殊情况,键的值不仅是String => Hash,而且是String => [Integer, Hash]

例如

["key1", "key2"]

关于哈希

{"key1" => [5, {"key2" => "BINGO!" }] }

应该再次返回"BINGO!",但仅包含的数组["key1"]将简单地返回5

4

2 回答 2

6

可能最简单的方法是使用inject

array.inject(hash) do |h, i|
  h.fetch(i){ {} }
end

# => "BINGO!"

fetch用于防止NoMethodError在哈希中不存在您的查找值之一的情况下出现。但是,在这种情况下,它将返回一个空哈希。您可能想要改为执行标准查找,即

array.inject(hash) {|h,i| h[i] }

编辑:

Here's an even shorter way to do this (I don't know if I would say it's 'more expressive', but it is shorter):

array.inject(hash, :[])
于 2013-03-31T00:42:09.043 回答
2

You can change the original answer a little bit for your second version of question:

array.inject(hash){ |h,i| h[i].is_a?(Array) ? h[i].last : h[i] }
于 2013-03-31T19:03:35.097 回答