[英]How to map with index in Ruby?
什么是最簡單的轉換方式
[x1, x2, x3, ... , xN]
至
[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
如果您正在使用ruby 1.8.7或1.9,則可以使用迭代器方法(如each_with_index
,在沒有塊的情況下調用時,返回一個Enumerator
對象,您可以調用Enumerable
方法,如map
on。 所以你可以這樣做:
arr.each_with_index.map { |x,i| [x, i+2] }
在1.8.6中你可以做到:
require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }
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]]
在ruby 1.9.3中有一個名為with_index
可鏈接方法,可以鏈接到map。
例如:
array.map.with_index { |item, index| ... }
在頂部混淆:
arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)
對於不使用枚舉器的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]]
我一直很喜歡這種風格的語法:
a = [1, 2, 3, 4]
a.each_with_index.map { |el, index| el + index }
# => [1, 3, 5, 7]
調用each_with_index
會為您提供一個枚舉器,您可以使用索引輕松映射該枚舉器。
a = [1, 2, 3]
p [a, (2...a.size+2).to_a].transpose
module Enumerable
def map_with_index(&block)
i = 0
self.map { |val|
val = block.call(val, i)
i += 1
val
}
end
end
["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]
這是一種有趣但無用的方法:
az = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}
我經常這樣做:
arr = ["a", "b", "c"]
(0...arr.length).map do |int|
[arr[int], int + 2]
end
#=> [["a", 2], ["b", 3], ["c", 4]]
您不是直接迭代數組的元素,而是迭代一系列整數並使用它們作為索引來檢索數組的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.