-2

Perl allows you to use the '..' operator to return a slice from an array. So if I wanted cells 4 through 8 from an array, I could this:

sample_array[4..8]

And if I assigned that to a new array, it would only have those 5 cells. Is there an operator like this for Ruby?

Thanks.

2
  • It can also be done as sample_array[4,8], which is actually faster. Commented Aug 26, 2010 at 22:55
  • @Jesse sample_array[4,8] is different from sample_array[4..8]. The first one starts at index 4 and grabs the next 8 indexes. The second one gets items at index 4 through 8.
    – Dty
    Commented Apr 7, 2011 at 16:22

3 Answers 3

1

You answered your own question. The Array#[] method can take a range, and return slices of that array.

1

You seem to have answered your own question, but fwiw, here is the Array#[] documentation which shows some more possibilities.

0

Hmm, wouldn't trying it yourself be faster than asking?

Yes, there's such operator. Working exactly like you described.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.