Home Ask Login Register

Developers Planet

Your answer is one click away!

Siper February 2016

Cut array after key in Ruby

I need to cut array after key in Ruby, for example:

=> ["Foo", "Bar", "Baz", "ooF", "raB", "zaB"] # Cut after "Baz"
=> ["Baz", "ooF", "raB", "zaB"] # result

It's possible to do? How can I do that?


Rustam A. Gasanov February 2016

Yes, just specify the range from index to -1(last element):

arr = ["Foo", "Bar", "Baz", "ooF", "raB", "zaB"]
arr[arr.index("Baz")..-1] # =>  ["Baz", "ooF", "raB", "zaB"]

Cary Swoveland February 2016

arr = ["Foo", "Bar", "Baz", "ooF", "raB", "zaB"]

arr.select { |s| s=='Baz'..nil ? 'Baz' : nil }
  #=> ["Baz", "ooF", "raB", "zaB"]

Look odd? What's going on here?

Wand Maker February 2016

Here is one more way to do this:

a = ["Foo", "Bar", "Baz", "ooF", "raB", "zaB"]

a.drop_while {|e| e != "Baz"}
#=> ["Baz", "ooF", "raB", "zaB"]

a.drop_while {|e| e != "Bazzzzzzz"}
#=> []

Post Status

Asked in February 2016
Viewed 2,049 times
Voted 12
Answered 3 times


Leave an answer

Quote of the day: live life