0
0
Rubyprogramming~10 mins

Select/filter for filtering in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Select/filter for filtering
Start with array
Check each element
Condition true?
NoSkip element
Yes
Add element to new array
More elements?
YesCheck next element
No
Return filtered array
The program checks each item in the array, keeps only those that meet the condition, and returns a new array with them.
Execution Sample
Ruby
numbers = [1, 2, 3, 4, 5]
even_numbers = numbers.select { |n| n.even? }
puts even_numbers
This code selects only even numbers from the list and prints them.
Execution Table
StepElement (n)Condition n.even?ActionFiltered Array
11falseSkip[]
22trueAdd 2[2]
33falseSkip[2]
44trueAdd 4[2, 4]
55falseSkip[2, 4]
6End-Return filtered array[2, 4]
💡 All elements checked, filtering complete.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
filtered_array[][][2][2][2, 4][2, 4][2, 4]
Key Moments - 2 Insights
Why is the number 1 not added to the filtered array?
Because at step 1 in the execution_table, the condition n.even? is false for 1, so it is skipped.
Does the original array change after select/filter?
No, the original array stays the same; select/filter creates a new array with only the matching elements, as shown by filtered_array starting empty and filling up.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4. What is the filtered array after adding element 4?
A[4]
B[2, 4]
C[2]
D[]
💡 Hint
Check the 'Filtered Array' column at step 4 in the execution_table.
At which step does the condition n.even? become false for the first time?
AStep 1
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Condition n.even?' column in the execution_table from the start.
If we changed the condition to n > 3, what would be the filtered array after step 5?
A[5]
B[2, 4]
C[4, 5]
D[1, 2, 3]
💡 Hint
Think about which numbers in the original array are greater than 3.
Concept Snapshot
Use select or filter to keep only elements that match a condition.
Syntax: array.select { |item| condition }
Returns a new array with matching items.
Original array stays unchanged.
Common for filtering lists easily.
Full Transcript
This visual execution shows how Ruby's select method filters an array. Starting with the array [1, 2, 3, 4, 5], each element is checked if it is even. If true, the element is added to a new array. Steps show 1 is skipped, 2 added, 3 skipped, 4 added, 5 skipped. The final filtered array is [2, 4]. The original array remains unchanged. This helps beginners see how select works step-by-step.