Can I split the array from text?

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?

···

--
Posted via http://www.ruby-forum.com/.

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

···

--
Posted via http://www.ruby-forum.com/.

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

···

--
Posted via http://www.ruby-forum.com/.

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]

···

--
Posted via http://www.ruby-forum.com/\.

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

···

--
Roger Braun
rbraun.net | humoralpathologie.de