Introduction
Array slicing lets you take parts of a list easily. Ranges help pick a group of items by their positions.
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)
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]
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]
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']
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(' ')}"
arr[1..3] do when arr = [10, 20, 30, 40, 50]?1..3 includes both 1 and 3, so it covers indexes 1, 2, and 3.arr[1..3] returns elements at indexes 1, 2, and 3, which are 20, 30, and 40.arr?... excludes the end index, so 2...5 means indexes 2, 3, and 4.arr[2...5] uses valid Ruby syntax for slicing excluding the end index.arr = [5, 10, 15, 20, 25] slice = arr[1...4] puts slice.inspect
1...4 includes indexes 1, 2, and 3 but excludes 4.arr = [1, 2, 3, 4, 5] slice = arr[2..6] puts slice.inspect
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?arr[1..5] gives [4, 6, 8, 10, 12].values_at with odd indexes on the slice correctly, returning [6, 10].Pass the test and this pattern moves unknown