在Ruby中组合数组的字符串元素

时间:2015-02-06 17:13:02

标签: ruby arrays string join

我有一个数组,此时此格式为["firstname1 ", "lastname1", "firstname2 ", "lastname2", etc],我正试图想出一种方法来组合字符串,以便我有一个数组["firstname1 lastname1", "firstname2 lastname2", etc]

2 个答案:

答案 0 :(得分:11)

使用Enumerable#each_slice,您可以迭代n元素片段(在您的情况下为2)。

通过加入这两个元素,您将得到您想要的东西。

a = ["firstname1 ", "lastname1", "firstname2 ", "lastname2"]
a.each_slice(2).map(&:join)
# => ["firstname1 lastname1", "firstname2 lastname2"]

答案 1 :(得分:1)

其他一些方式:

a = ["Shirley ", "Temple", "Oliver ", "Hardy", "John ", "Wayne"]

<强>#1

(0...a.size).step(2).map { |i| a[i]+a[i+1] }
  #=> ["Shirley Temple", "Oliver Hardy", "John Wayne"]

<强>#2

enum = a.to_enum
(a.size/2).times.map { enum.next + enum.next }
  #=> ["Shirley Temple", "Oliver Hardy", "John Wayne"]

<强>#2a中

enum = a.to_enum
names = []
loop { names << enum.next + enum.next }
names
  #=> ["Shirley Temple", "Oliver Hardy", "John Wayne"]

<强>#3

fname = nil
a.each_with_object([]) { |s,a| (s[-1]==' ') ? fname=s : a << fname+s }
  #=> ["Shirley Temple", "Stan Laurel", "John Wayne"]