0
0
Rubyprogramming~10 mins

Accessing elements (indexing, first, last) in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Accessing elements (indexing, first, last)
Start with Array
Choose index or method
Indexing: array[index
Return element at index
First element: array.first
Return first element
Last element: array.last
Return last element
Start with an array, then access elements by index, or use .first or .last methods to get the first or last element.
Execution Sample
Ruby
arr = [10, 20, 30, 40]
puts arr[1]
puts arr.first
puts arr.last
This code prints the second element, then the first, then the last element of the array.
Execution Table
StepExpressionEvaluationResultOutput
1arr = [10, 20, 30, 40]Assign array to arr[10, 20, 30, 40]
2arr[1]Access element at index 12020
3arr.firstGet first element1010
4arr.lastGet last element4040
5EndNo more expressions
💡 All expressions evaluated, program ends.
Variable Tracker
VariableStartAfter Step 1After Step 5
arrundefined[10, 20, 30, 40][10, 20, 30, 40]
Key Moments - 2 Insights
Why does arr[1] return 20 and not 10?
In Ruby, array indexing starts at 0, so arr[0] is 10, arr[1] is 20 as shown in step 2 of the execution_table.
What happens if I use arr.first on an empty array?
arr.first returns nil if the array is empty, because there is no first element. In Ruby, indexing out of range also returns nil.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of arr[1] at step 2?
A20
B10
C30
D40
💡 Hint
Check the 'Result' and 'Output' columns in row for step 2.
At which step do we get the last element of the array?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for the expression using arr.last in the execution_table.
If we change arr to [5, 15, 25], what would arr.first return?
A15
B5
C25
Dnil
💡 Hint
Refer to variable_tracker and remember arr.first returns the first element.
Concept Snapshot
Access elements in Ruby arrays using indexing or methods:
- array[index]: zero-based index access
- array.first: returns first element
- array.last: returns last element
Indexing out of range returns nil
.first and .last are safe for empty arrays
Full Transcript
This lesson shows how to get elements from a Ruby array. You can use array[index] where index starts at 0. For example, arr[1] gets the second element. You can also use arr.first to get the first element and arr.last to get the last element. These methods return nil if the array is empty, which is safe. The example code creates an array with four numbers and prints the second, first, and last elements. The execution table shows each step and the output. Remember, indexing starts at zero, so arr[0] is the first element. This helps you pick any element you want from an array easily.