0
0
Rubyprogramming~10 mins

Array slicing and ranges in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get the first three elements of the array.

Ruby
arr = [10, 20, 30, 40, 50]
slice = arr[[1]]
Drag options to blanks, or click blank then click option'
A1..3
B0..2
C2..4
D3..5
Attempts:
3 left
💡 Hint
Common Mistakes
Using a range starting at 1 misses the first element.
Using an exclusive range (0...2) only gets two elements.
2fill in blank
medium

Complete the code to get the last two elements of the array.

Ruby
arr = [5, 10, 15, 20, 25]
slice = arr[[1]]
Drag options to blanks, or click blank then click option'
A-2..-1
B-3..-1
C3..4
D2..3
Attempts:
3 left
💡 Hint
Common Mistakes
Using -3..-1 gets three elements instead of two.
Using positive indexes may be less clear for the last elements.
3fill in blank
hard

Fix the error in the code to slice the array from index 1 to 3 inclusive.

Ruby
arr = [2, 4, 6, 8, 10]
slice = arr[[1]]
Drag options to blanks, or click blank then click option'
A1...3
B0..2
C2..4
D1..3
Attempts:
3 left
💡 Hint
Common Mistakes
Using a triple dot range excludes the last element.
Using wrong indexes results in wrong slice.
4fill in blank
hard

Fill both blanks to create a slice from the second to the fourth element (inclusive).

Ruby
arr = ['a', 'b', 'c', 'd', 'e']
slice = arr[[1]..[2]]
Drag options to blanks, or click blank then click option'
A1
B2
C3
D4
Attempts:
3 left
💡 Hint
Common Mistakes
Using 2 as start misses the second element.
Using 4 as end includes the fifth element.
5fill in blank
hard

Fill all three blanks to create a slice from the third element to the last element.

Ruby
arr = [100, 200, 300, 400, 500]
slice = arr[[1]..[2]]
puts slice[[3]]
Drag options to blanks, or click blank then click option'
A2
B4
C0
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using 3 as start misses the third element.
Using 3 as end excludes the last element.
Using 2 as slice index causes wrong output.