Bird
Raised Fist0
Rubyprogramming~5 mins

Array slicing and ranges in Ruby

Choose your learning style10 modes available
Introduction
Array slicing lets you take parts of a list easily. Ranges help pick a group of items by their positions.
You want to get the first few items from a list, like the first 3 fruits.
You want to get the last few items, like the last 2 days of the week.
You want to get a middle part, like days 2 to 4 from a list of days.
You want to loop over a part of an array without changing the original.
You want to check or change a section of an array quickly.
Syntax
Ruby
class Array
  # Get a slice using a range
  def slice(range)
    # returns a new array with elements from range
  end
end

# Using range to slice
array[start_index..end_index]  # inclusive range
array[start_index...end_index] # exclusive range

# Using slice method
array.slice(range)

# Using slice with start and length
array.slice(start_index, length)
Ranges use two dots (..) to include the end index, and three dots (...) to exclude it.
Array indices start at 0 in Ruby.
Examples
Shows how to use inclusive and exclusive ranges to get parts of the array.
Ruby
fruits = ['apple', 'banana', 'cherry', 'date', 'fig']

# Get first 3 fruits
first_three = fruits[0..2]

# Get fruits from index 2 to 4
middle_fruits = fruits[2..4]

# Get fruits from index 1 to 3 (excluding 3)
partial_fruits = fruits[1...3]
Shows slice with start and length, and edge cases with empty and single element arrays.
Ruby
numbers = [10, 20, 30, 40, 50]

# Slice with start and length
slice_part = numbers.slice(1, 3)  # gets elements at index 1,2,3

# Edge case: empty array
empty = [].slice(0..2)  # returns []

# Edge case: single element array
single = [99].slice(0..0)  # returns [99]
Shows slicing with negative indices and slicing beyond array size.
Ruby
letters = ['a', 'b', 'c', 'd']

# Slice from start to end
all_letters = letters[0..-1]  # gets all elements

# Slice last two elements
last_two = letters[-2..-1]

# Edge case: slice beyond array size
beyond = letters[2..10]  # returns ['c', 'd']
Sample Program
This program shows how to slice arrays using ranges in Ruby. It prints the original array, slices parts of it, and shows edge cases with empty and single element arrays.
Ruby
fruits = ['apple', 'banana', 'cherry', 'date', 'fig']

puts "Original array: #{fruits.join(' ')}"

# Slice first 3 fruits
first_three = fruits[0..2]
puts "First three fruits: #{first_three.join(' ')}"

# Slice middle fruits
middle_fruits = fruits[1...4]
puts "Middle fruits (index 1 to 3): #{middle_fruits.join(' ')}"

# Slice last two fruits
last_two = fruits[-2..-1]
puts "Last two fruits: #{last_two.join(' ')}"

# Edge case: slice empty array
empty_array = []
empty_slice = empty_array[0..2]
puts "Slice from empty array: #{empty_slice.join(' ')}"

# Edge case: slice single element array
single_array = ['kiwi']
single_slice = single_array[0..0]
puts "Slice single element array: #{single_slice.join(' ')}"
OutputSuccess
Important Notes
Time complexity of slicing is O(k), where k is the number of elements in the slice.
Space complexity is O(k) because a new array is created for the slice.
Common mistake: forgetting that ranges with two dots include the end index, while three dots exclude it.
Use slicing when you want a new array with part of the elements. Use other methods like 'select' if you want to filter by condition.
Summary
Array slicing lets you get parts of an array easily using ranges.
Ranges with '..' include the end index; '...' excludes it.
Slicing creates a new array and does not change the original.

Practice

(1/5)
1. What does the expression arr[1..3] do when arr = [10, 20, 30, 40, 50]?
easy
A. Returns a new array with elements at indexes 1, 2, and 3
B. Returns a new array with elements at indexes 1 and 3 only
C. Returns a new array with elements at indexes 1 and 2 only
D. Returns a single element at index 3

Solution

  1. Step 1: Understand the range operator '..'

    The range 1..3 includes both 1 and 3, so it covers indexes 1, 2, and 3.
  2. Step 2: Apply slicing to the array

    Slicing arr[1..3] returns elements at indexes 1, 2, and 3, which are 20, 30, and 40.
  3. Final Answer:

    Returns a new array with elements at indexes 1, 2, and 3 -> Option A
  4. Quick Check:

    Range '..' includes end index = elements 20, 30, 40 [OK]
Hint: Remember '..' includes the end index in slicing [OK]
Common Mistakes:
  • Thinking '..' excludes the end index
  • Confusing indexes with values
  • Assuming slicing changes the original array
2. Which of the following is the correct syntax to get elements from index 2 up to but not including index 5 in Ruby array arr?
easy
A. arr[2...5]
B. arr[2:5]
C. arr[2..5]
D. arr[2-5]

Solution

  1. Step 1: Identify the range operator for excluding end

    In Ruby, ... excludes the end index, so 2...5 means indexes 2, 3, and 4.
  2. Step 2: Check syntax correctness

    Only arr[2...5] uses valid Ruby syntax for slicing excluding the end index.
  3. Final Answer:

    arr[2...5] -> Option A
  4. Quick Check:

    Use '...' to exclude end index in range [OK]
Hint: Use '...' to exclude the last index in range slicing [OK]
Common Mistakes:
  • Using '..' when exclusion is needed
  • Using Python-style slicing syntax like ':'
  • Using invalid range syntax like '2-5'
3. What is the output of the following Ruby code?
arr = [5, 10, 15, 20, 25]
slice = arr[1...4]
puts slice.inspect
medium
A. [10, 15, 20, 25]
B. [15, 20, 25]
C. [10, 15, 20]
D. [5, 10, 15]

Solution

  1. Step 1: Understand the slicing range

    The range 1...4 includes indexes 1, 2, and 3 but excludes 4.
  2. Step 2: Extract elements at these indexes

    Elements at indexes 1, 2, 3 are 10, 15, and 20 respectively.
  3. Final Answer:

    [10, 15, 20] -> Option C
  4. Quick Check:

    Range '...' excludes end index = [10, 15, 20] [OK]
Hint: Remember '...' excludes the last index in slicing [OK]
Common Mistakes:
  • Including element at index 4 mistakenly
  • Confusing indexes with values
  • Printing original array instead of slice
4. Identify the error in the following Ruby code snippet:
arr = [1, 2, 3, 4, 5]
slice = arr[2..6]
puts slice.inspect
medium
A. Syntax error due to invalid range
B. Range end index 6 is out of bounds but Ruby returns elements up to the end of the array
C. Runtime error because index 6 does not exist
D. slice will be empty array because range is invalid

Solution

  1. Step 1: Check the range indexes against array size

    The array has indexes 0 to 4. The range 2..6 goes beyond the last index.
  2. Step 2: Understand Ruby slicing behavior for out-of-bounds

    Ruby returns elements from index 2 to the end (indexes 2, 3, 4) and ignores indexes beyond 4 without error.
  3. Final Answer:

    Range end index 6 is out of bounds but Ruby returns elements up to the end of the array -> Option B
  4. Quick Check:

    Ruby slices safely even if range exceeds array size [OK]
Hint: Ruby slicing ignores out-of-bound indexes without error [OK]
Common Mistakes:
  • Expecting runtime or syntax error
  • Assuming slice will be empty
  • Confusing Ruby with other languages that error here
5. Given arr = [2, 4, 6, 8, 10, 12], which expression returns a new array with every second element starting from index 1 up to index 5?
hard
A. arr[1..5].select.with_index { |_, i| i.even? }
B. arr[1..5].select.with_index { |_, i| i.odd? }
C. arr[1...6].values_at(*arr[1...6].each_index.select(&:even?))
D. arr[1..5].values_at(*arr[1..5].each_index.select(&:odd?))

Solution

  1. Step 1: Slice array from index 1 to 5

    arr[1..5] gives [4, 6, 8, 10, 12].
  2. Step 2: Select every second element starting from index 1 of the slice

    Indexes inside the slice are 0 to 4. Selecting odd indexes (1, 3) gives elements 6 and 10.
  3. Step 3: Check options for correct syntax and output

    arr[1..5].values_at(*arr[1..5].each_index.select(&:odd?)) uses values_at with odd indexes on the slice correctly, returning [6, 10].
  4. Final Answer:

    arr[1..5].values_at(*arr[1..5].each_index.select(&:odd?)) -> Option D
  5. Quick Check:

    Use values_at with odd indexes on slice for every second element [OK]
Hint: Use values_at with selected indexes for custom slicing [OK]
Common Mistakes:
  • Confusing odd/even indexes inside the slice
  • Using select without values_at returns elements, not indexes
  • Using wrong range operator causing off-by-one errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard