Ruby中的矢量化字符串连接就像R的粘贴功能一样

时间:2012-11-30 15:58:21

标签: ruby arrays

我在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"] 

1 个答案:

答案 0 :(得分: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的版本适用于多个阵列。