如何在Ruby中使用索引进行映射?

Mis*_*hko 420 ruby arrays indexing

什么是最简单的转换方式

[x1, x2, x3, ... , xN]
Run Code Online (Sandbox Code Playgroud)

[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 804

如果您正在使用ruby 1.8.7或1.9,则可以使用迭代器方法这样的事实,例如each_with_index,在没有块的情况下调用时,返回一个Enumerator对象,您可以调用Enumerablemapon 这样的方法.所以你可以这样做:

arr.each_with_index.map { |x,i| [x, i+2] }
Run Code Online (Sandbox Code Playgroud)

在1.8.6中你可以做到:

require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }
Run Code Online (Sandbox Code Playgroud)

  • IMO在1.8.7+中更简单,更好读:`arr.map.with_index {| o,i | [o,i + 2]}` (8认同)
  • @Phrogz:`map.with_index`在1.8.7中不起作用(`map`在1.8中没有块时调用返回一个数组). (4认同)
  • @Misha:`map` 一如既往地是`Enumerable` 的一种方法。`each_with_index`,在没有块的情况下调用时,返回一个 `Enumerator` 对象(在 1.8.7+ 中),它混合在 `Enumerable` 中,因此您可以在其上调用 `map`、`select`、`reject` 等就像在数组、散列、范围等上一样。 (2认同)
  • 重要的是要注意这不适用于.map!如果你想直接影响你正在循环的数组. (2认同)

tok*_*and 245

Ruby有Enumerator #with_index(offset = 0),所以首先使用Object#to_enumArray#map将数组转换为枚举器:

[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]
Run Code Online (Sandbox Code Playgroud)

  • 我相信这是更好的答案,因为它可以与地图一起使用!`foo = ['d']*5; foo.map!.with_index {| x,i | x*i}; foo#=> ["","d","dd","ddd","dddd"]` (11认同)

fru*_*uqi 115

在ruby 1.9.3中,有一个可链接的方法with_index,可以链接到map.

例如: with_index


And*_*imm 16

在顶部混淆:

arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)
Run Code Online (Sandbox Code Playgroud)

  • 安德鲁必须有出色的工作保障!:) (11认同)
  • 我喜欢那个,晦涩难懂的代码总是很有趣. (10认同)

Phr*_*ogz 9

对于不使用枚举器的1.8.6(或1.9),还有两个选项:

# Fun with functional
arr = ('a'..'g').to_a
arr.zip( (2..(arr.length+2)).to_a )
#=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]

# The simplest
n = 1
arr.map{ |c| [c, n+=1 ] }
#=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]
Run Code Online (Sandbox Code Playgroud)


ybu*_*yug 8

我一直很喜欢这种风格的语法:

a = [1, 2, 3, 4]
a.each_with_index.map { |el, index| el + index }
# => [1, 3, 5, 7]
Run Code Online (Sandbox Code Playgroud)

调用each_with_index会为您提供一个枚举器,您可以使用索引轻松映射它.

  • 这个不同的形式是什么[答案,差不多5年才给你](http://stackoverflow.com/a/4697573/1772830)? (4认同)

Aut*_*ico 5

一个有趣但没用的方法来做到这一点:

az  = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}
Run Code Online (Sandbox Code Playgroud)

  • 当我写“一种有趣但无用的方式”时。`+2` 是创建 OP 要求的输出 (3认同)