Can I split the array from text?

S

Sira PS

If I have an array like this

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

And I need to split this array from "Components" and get 2 arrays which
are

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

and

["Family", "Lastname"]

Can I do that and how?
 
J

Joey Zhou

Maybe you can refer to Enumerable#slice_before

Here's a sample code:

a = ["Member","Friends","Hello","Components","Family","Lastname"]
b = a.slice_before {|elem| elem == "Components" }.to_a
p b[0] #=> ["Member", "Friends", "Hello"]
p b[1] #=> ["Components", "Family", "Lastname"]

Joey
 
J

Joey Zhou

Here's a tricky one:)

a = ["Member","Friends","Hello","Components","Family","Lastname"]
b = a.partition {|elem| true unless elem=="Components"..false }
p b
#=> [["Member","Friends","Hello"], ["Components","Family",
"Lastname"]]
 
R

Roger Braun

How about this?

module Enumerable

def split(sep = nil)
res = Array.new
part = Array.new

self.each do |el|
if block_given? ? yield(el) : el === sep then
res.push(part)
part = Array.new
else
part.push(el)
end
end

res.push(part)

res
end

end

ruby-1.9.2-p180 :015 > ar = ["Member", "Friends", "Hello",
"Components", "Family", "Lastname"]
=> ["Member", "Friends", "Hello", "Components", "Family", "Lastname"]
ruby-1.9.2-p180 :016 > ar.split("Friends")
=> [["Member"], ["Hello", "Components", "Family", "Lastname"]]
ruby-1.9.2-p180 :017 > ar.split do |el| el[-1] == "s" end
=> [["Member"], ["Hello"], ["Family", "Lastname"]]
 
B

Brian Candler

Sira PS wrote in post #994712:
If I have an array like this

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

And I need to split this array from "Components" and get 2 arrays which
are

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

and

["Family", "Lastname"]

Can I do that and how?

I think this is the simplest way:

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top