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.
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.
[0, 1, 2, 3, 4][1..]slice to be a bit more explicit and it's less confusing to people coming from a non-Ruby background.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.
1the first element or the second? Because array indices are zero-based.addressesis a relation and there are many entries you might want to useuser.addresses.offset(1).limit(4)which turns that into a database query.