If I have an array like this
开发者_开发技巧["Member", "Friends", "Hello", "Components", "Family", "Lastname"]
and I need to split it at "Components"
and get 2 arrays, which are
["Member", "Friends", "Hello"]
and
["Family", "Lastname"]
Can I do that and how?
You can use 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
In ruby 1.9 (because of chunk method):
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"]
May be by
i = ary.index["Components"] - 1
ary[0..i] #=>["Member", "Friends", "Hello"]
i = ary.index["Components"] + 1
ary[i..ary.length] #=>["Family", "Lastname"]
or
ary[0..ary.index["Components"]-1] #=>["Member", "Friends", "Hello"]
ary[ary.index["Components"]+1..ary.length] #=>["Family", "Lastname"]
Also can use:
i = ary.index["Components"] - 1
ary.take(i) #=>["Member", "Friends", "Hello"]
newArray = oldArray.slice(5,2)
use the index and length methods to work out the 5 and 2 values
should leave you with:
newArray ["Family", "Lastname"]
oldArray ["Member", "Friends", "Hello"]
see the doc here: http://www.ruby-doc.org/core-1.8.3/classes/Array.html#M000398
As an method:
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"]
or inliner
array = ["Member", "Friends", "Hello", "Components", "Family", "Lastname"]
first, second = array[0, a.index("Components")], a[a.index("Components")+1..-1]
精彩评论