使用 .map 函数创建哈希



>我有一个数组[5,2,6,4],我想创建一个结构,例如第一个减去第二个等,直到最后一行。

我尝试使用地图,但不确定如何继续,因为我可能需要 indxes。

我想将结果存储在如下所示的内容中:

{1 => (5, 2, 3), 2 =>(2,6,-4), 3 => (6,4,2)}

因此,x数组应返回x-1哈希。有人知道该怎么做吗?应该是一个简单的。谢谢。

首先,您希望成对使用数组元素:5,22,6、...这意味着您要使用each_cons

a.each_cons(2) { |(e1, e2)| ... }

然后你会希望索引得到12、...哈希键;这表明将Enumerator#with_index投入其中:

a.each_cons(2).with_index { |(e1, e2), i| ... }

然后,您可以使用with_object来发挥最终部分(哈希(:

a.each_cons(2).with_index.with_object({}) { |((e1, e2), i), h| h[i + 1] = [e1, e2, e1 - e2] }

如果您认为块参数中的所有括号都太嘈杂,那么您可以分步完成,而不是单行。

您可以使用

each_index

a = [5, 2, 6, 4]
h = {}
a[0..-2].each_index { |i| h[i+1] = [a[i], a[i+1], a[i] - a[i+1]] } 
h
 => {1=>[5, 2, 3], 2=>[2, 6, -4], 3=>[6, 4, 2]} 

尝试使用

 each_with_index

假设你有一个数组:

arr = [3,[2,3],4,5]

并且您想用哈希(键值对(来掩盖。"键"表示数组的索引,"值"表示数组的值。取一个空白哈希并使用each_with_index迭代并推送到哈希中,最后打印哈希。

试试这个:

hash={}
arr.each_with_index do |val, index|
    hash[index]=val
end
p hash

其输出将是:

{0=>3, 1=>[2, 3], 2=>4, 3=>5}

如果您希望索引始终以 1 或 2 等开头,请使用

arr.each.with_index(1) do |val, index|
    hash[index] = val
end

输出将是:

{1=>3, 2=>[2, 3], 3=>4, 4=>5}

最新更新