我可以从文本中拆分数组吗?

时间:2011-04-24 07:57:53

标签: ruby-on-rails ruby

如果我有这样的数组

["Member", "Friends", "Hello", "Components", "Family", "Lastname"]

我需要将其拆分为"Components"并获取2个数组,即

["Member", "Friends", "Hello"]

["Family", "Lastname"]

我可以这样做吗?

5 个答案:

答案 0 :(得分:5)

您可以使用Array#slice

class Array
  def msplit(m)
    idx = self.index(m)
    idx ? [self[0..idx-1], self[idx+1..-1]] : nil
  end
end

arr = ["Member", "Friends", "Hello", "Components", "Family", "Lastname"]
a, b = arr.msplit("Components")
a # => ["Member", "Friends", "Hello"]
b # => ["Family", "Lastname"]
a.msplit("Foo") # => nil

答案 1 :(得分:1)

在ruby 1.9中(由于chunk方法):

array = ["Member", "Friends", "Hello", "Components", "Family", "Lastname"]
a, b = array.chunk {|e| e != "Components"}.map {|a, b| b if a}.compact
p a, b #=> ["Member", "Friends", "Hello"] ["Family", "Lastname"]

答案 2 :(得分:0)

可能是

i = ary.index["Components"] - 1
ary[0..i]            #=>["Member", "Friends", "Hello"]
i = ary.index["Components"] + 1
ary[i..ary.length]   #=>["Family", "Lastname"]

ary[0..ary.index["Components"]-1]            #=>["Member", "Friends", "Hello"]
ary[ary.index["Components"]+1..ary.length]   #=>["Family", "Lastname"]

也可以使用:

i = ary.index["Components"] - 1
ary.take(i)          #=>["Member", "Friends", "Hello"]

答案 3 :(得分:0)

newArray = oldArray.slice(5,2)

使用索引和长度方法计算5和2值

应该留给你:

newArray [“家庭”,“姓氏”]

oldArray [“会员”,“朋友”,“你好”]

请参阅此处的文档:http://www.ruby-doc.org/core-1.8.3/classes/Array.html#M000398

答案 4 :(得分:0)

作为一种方法:

class Array
  def split_by(val)
    [0, a.index(val)], a[a.index(val)+1..-1]
  end
end

array = ["Member", "Friends", "Hello", "Components", "Family", "Lastname"]
first, second = array.split_by("Complonents")
first
#=> ["Member", "Friends", "Hello"] 
second
#=> ["Family", "Lastname"]

或inliner

array = ["Member", "Friends", "Hello", "Components", "Family", "Lastname"]
first, second = array[0, a.index("Components")], a[a.index("Components")+1..-1]