RFS: Loops and Iterators Part 2 - 015

We'll be taking loops and iterators episode a little bit further. In this episode we'll look at some iterators that are commonly used in ruby.

.map

.map is probably one of the most powerful iterators. What it will allow you to do is, perform some kind of operation on a collection of items and returns a collection or an array of the results.

numbers = [1, 3, 6, 9]squared = numbers.map do |x|  x * xendp squared=> [1, 6, 36, 81]

If you use puts the result might look like it just put out a list of string this is because puts apply a to_s to he array.

.reject

If you have an array and what to 'reject' some values based on certain conditions you can use the .reject method on the array.

p numbers.reject { |x| (x * x) < 36 }=> [6, 9]

This will out put the values in the numbers that is less than 36 after being squared. In this case [1, 3] will be rejected outputting [6, 9]

.select

The .select method is exactly the opposite of reject it will only return the values that match a certain condition supplied in the block.

equals_six = numbers.select do |x|  x == 6endp equals_six => [6]

That's it for this episode, if you like what you see here and would like to see us cover more iterators please let us know!