问题描述
我有一个2维数组
v = [[ab,12],[ab ,31],[gh,54]]
v的子数组将具有重复元素,例如ab
。我想创建一个散列,将键作为子数组的第一个元素,并将值作为来自 v
的相应第二个元素的数组。 b
请指教。
另外,我想这个,h = {ab=> [12,31], gh=> [54]}然后我想返回h.values,这样返回数组[[12,31],[54]]
v.inject(Hash.new {| h,k | h [k] = []}) {| h,(k,v)| h [k]<< v; h}
功能:
-
。 Wikipedia定义了这样的折叠:一系列高阶函数,它们分析递归数据结构,并通过使用给定的组合操作重组处理其组成部分的结果,建立返回值 。
-
带有两个参数,散列本身和密钥。如果您的默认参数是可变对象,则必须以此方式设置默认值,否则所有键都将指向同一个数组实例。
c $ c>注入的块,我们得到两个参数,散列值和迭代的当前值。由于这是一个二元数组,因此使用 -
最后,我们将每个值添加到数组中作为其键,并返回整个哈希值以用于下一次迭代。
(k,v)
将后者解构为两个变量。 I have a 2 dimensional array
v = [ ["ab","12"], ["ab","31"], ["gh","54"] ]
The first element of the subarray of v will have repeating elements, such as "ab"
. I want to create a hash that puts the key as the first element of the subarray, and values as an array of corresponding second elements from v
.
please advice.
Further, I want this, h={"ab"=>["12","31"],"gh"=>["54"]} and then I want to return h.values, such that the array [["12","31"],["54"]] is returned
v.inject(Hash.new{|h,k|h[k]=[]}) { |h, (k, v)| h[k] << v ; h}
What it does:
inject (also called
reduce
) is a fold. Wikipedia defines folds like this: "a family of higher-order functions that analyze a recursive data structure and recombine through use of a given combining operation the results of recursively processing its constituent parts, building up a return value".The block form of Hash.new takes two arguments, the hash itself and the key. If your default argument is a mutable object, you have to set the default this way, otherwise all keys will point to the same array instance.
In
inject
's block, we get two arguments, the hash and the current value of the iteration. Since this is a two element array,(k, v)
is used to destructure the latter into two variables.Finally we add each value to the array for its key and return the entire hash for the next iteration.
这篇关于从2维数组中提取数据并创建一个包含数组值的散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!