4

我在 Ruby 中有两个数组,我想将它们按元素连接在一起。在 R 中,这就像使用paste函数一样简单,因为它是矢量化的:

# R
values <- c(1, 2, 3)
names <- c("one", "two", "three")
paste(values, names, sep = " as ")
[1] "1 as one"   "2 as two"   "3 as three"

在Ruby中它有点复杂,我想知道是否有更直接的方法:

# Ruby
values = [1, 2, 3]
names = ["one", "two", "three"]
values.zip(names).map { |zipped| zipped.join(" as ") }
 => ["1 as one", "2 as two", "3 as three"] 
4

1 回答 1

3

另一种方法:

values = [1, 2, 3]
names = ["one", "two", "three"].to_enum 
values.map{|v|"#{v} as #{names.next}"}
# => ["1 as one", "2 as two", "3 as three"]

然而,这会在超过 2 个数组时变得更加复杂。OP 的版本更适用于多个数组。

于 2012-11-30T16:32:07.553 回答