Ruby Iterators
Short intro into the ruby iteration methods. Some are uncommon and special.
Created Sep 28, 2024 - Last updated: Nov 22, 2024
🟧
ruby
iterator
blocks
- loops and iterators are different
- ruby has some special iterators
- iterators operate on arrays and ranges and procs
- break can be used to break out of the iterator
Common Methods
each
[1,2,3].each {|x| x*2}
# [2,4,6] => [1,2,3]
takes each element and operates
Returns the original array
collect
[1,2,3].collect {|x| x*2}
# [2,4,6]
transforms the array
returns the transformed array
select
[1,2,3].select { |x| (x % 2) == 0 }
# [2]
filters the array based on the conditions in block
returns the filtered list of the array
inject
[1,2,3].inject(1) {|result, item| result + item}
# 7
injects the value and does an inner loop returns the result