1

I have an array of objects and would like to take items 1 through 4 but take doesn't accept a range.

user.addresses.take(1...4)

What's a way to achieve this? In Rails so if there's some ActiveSupport addition, I could use that too.

3
  • Is 1 the first element or the second? Because array indices are zero-based. Commented Jun 30, 2021 at 5:39
  • @Stefan in this case, second. Commented Jun 30, 2021 at 16:23
  • 1
    If addresses is a relation and there are many entries you might want to use user.addresses.offset(1).limit(4) which turns that into a database query. Commented Jun 30, 2021 at 17:27

1 Answer 1

6

Ruby's take method accepts a single integer value for the number of elements to take. Calling [0, 1, 2, 3, 4].take(4) will return the 0th, 1st, 2nd, and 3rd element of the array, or [0, 1, 2, 3].

If you want to skip the 0th element, you can consider slice. Calling [0, 1, 2, 3, 4].slice(1..) will return [1, 2, 3, 4]. You can limit the range to take a subset. You can also use [] as a method on the array, as slice is an alias for []. The infinite range syntax of x.. was introduced in Ruby 2.6. In earlier versions of Ruby, you could accomplish this with 1..-1 instead.

Sign up to request clarification or add additional context in comments.

3 Comments

Or more concisely as simply: [0, 1, 2, 3, 4][1..]
@ChrisDutton Yes, I'll add that. I normally prefer slice to be a bit more explicit and it's less confusing to people coming from a non-Ruby background.
For a more descriptive approach there's also ary.drop(1).take(4) but most of the time you'll see ary[1, 4] (take 4 starting at 1) or ary[1..4] (take elements 1 to 4) due to brevity.

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.