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对象,您可以调用Enumerable像mapon 这样的方法.所以你可以这样做:
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)
tok*_*and 245
Ruby有Enumerator #with_index(offset = 0),所以首先使用Object#to_enum或Array#map将数组转换为枚举器:
[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]
Run Code Online (Sandbox Code Playgroud)
And*_*imm 16
在顶部混淆:
arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)
Run Code Online (Sandbox Code Playgroud)
对于不使用枚举器的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)
我一直很喜欢这种风格的语法:
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会为您提供一个枚举器,您可以使用索引轻松映射它.
一个有趣但没用的方法来做到这一点:
az = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
199119 次 |
| 最近记录: |