Ruby Iterators
Iterators are Ruby methods that are called on collections, that is hashes, arrays, etc. A loop runs a block of code for a certain number of times while an iterator run a block of code on a data set.
You’d call an iterator on a collection when you want to run some logic on each element of said collection and return a value.
Ruby iterators are chainable, just like most Ruby methods.
each
array = [ 1, 2, 3]array.each do |num|
puts num + 5
end# 6
# 7
# 8
you can also define and call the iterator in one step
[ 1, 2, 3].each do |num|
puts num + 5
end# 6
# 7
# 8
The each iterator returns all elements in a collection after running a block of code on them.
collect
array_one = [ 1, 2, 3]array_two = Array.newarray_two = array_one.collectputs array_two# 1
# 2
# 3
The collect iterator returns all elements of a collection after running a block of code on each element.
collect/map
array = [1, 2, 3]array.map do |element|
element + 1
end# [2, 3, 4]array
# [1, 2, 3]
You can use map or collect, different names but they’re the same thing, I prefer map but you do you.
The difference between each and map, is that map returns a new object. That is deal when you don’t want to modify the original object but create a new one instead. If you add an exclamation sign ! it’ll overwrite the original array so use with care.
times
3.times do
puts 'hello World'
end# Hello World
# Hello World
# Hello World3.times do |num|
puts 'hello World ' + num + '.'
end# Hello World 0.
# Hello World 1.
# Hello World 2.
Times is super simple, it repeats a block of code a certain number of times and you can even pass it a parameter to access the ‘time’ it’s running.
select and find
array = [1, 2, 3, 4, 5]array.select do |element|
element.odd?
end# [1, 3, 5]
Select will ‘select’ all the elements that meet a certain criteria, in this case it’ll pick all the odd numbers. Find has a similar syntax but it will only return the first element that meets the criteria.
all? and any?
array = [1, 2, 3, 4, 5]array.all? do |element|
element.odd?
end# falsearray = [1, 2, 3, 4, 5]array.any? do |element|
element.odd?
end# true
Both these methods return a boolean value if the search criteria is met. All? will return true when all the elements meet the criteria while any? returns true if any of the elements meet it.
I hope this little article helped you get an idea on how to use Ruby iterators and the simple syntax needed to make them run. Happy coding!