1

Is it possible to apply a sub range to an array in ruby like this:

 > array = [4, 3, 2, 1]
 > array[0...2]
=> [4, 3]

if the [0...2] is stored in a variable? I can't seem to get a syntax to give me what I want. What replaces the <?> in the following, if anything?

 > array = [4, 3, 2, 1]
 > range = [0...2]
 > array<?>
=> [4, 3]
0

2 Answers 2

3

Yes, sure! Do this way:

array = [4, 3, 2, 1]
exclusive_range = [0...2] # Will get 0th and 1st element of the array
inclusive_range = [0..2] # Will get 0th, 1st and 2nd element of the array
array[exclusive_range.first]
# => [4, 3]
array[inclusive_range.first] 
# => [4, 3, 2]

If you want to avoid .first call, you can put your range in a variable (Not in an array):

range = 0...2
array[range]
# => [4, 3]
Sign up to request clarification or add additional context in comments.

4 Comments

Very interesting! Why must we call first on it?
Because your range (0...2) is the first element of exclusive_range array.
Look at my updated answer, that way if you define the range just as a variable not in an array, then you don't need to call: range.first. Let me know if you any other question.
@JakeSmith: Because your range variable does not point to a Range object, it points to an Array object with a single element which is a Range object. Square brackets [] denote an Array literal. You could fix this by assigning a Range to the range variable instead of an Array of Ranges.
1

Note that (0..2).size #=> 3. If you want to return [4,3] you want:

range = 0..1

You could use it like this:

array[range]           #=> [4, 3]

or like this:

array.values_at *range #=> [4, 3]

Comments

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.