Ruby!

Enumerables and Enumerators

Part 1: #map and #select

Give it to me short and sweet.

Basically, #map takes any collection, and cycles through it, applying whatever block of code you've specified to that collection, and returning an array.

Tell me more, tell me more!

Very simply put, an enumerable is a type of class in ruby that represents a collection of things. Enumerables and enumerators (their methods, or verbs) are all about iteration. Enumerables can be iterated over, and enumerators iterate over them.

Howabout some practical application?

One of the important things to remember at the outset with #map is that it returns an array. So, any time you need to return an array, an enumerator like #map (or #select) is a great way to go.

Picture this: You're solving a problem, and the clearest way to do it seems to be to use the #each operator, but you really need a place to put the results that #each produces, so you create a new array before iterating, and shovel the results of each #each cycle into that array, and then return that array when you're done.

new_array = []
	array.each do |x|
		array << (x * 3)
	end

Guess what?

You basically just implimented #map.

array.map {|x| x * 3}

Nifty! What is this #select you speak of?

#select is like map, in that returns an array (read: super useful). #select is particularly useful because it will siphon off elements of the array it is called on, based on whether the block it's fed returns true or false.

Picture this: you want to iterate through an array, and return an array... but you need to be picky with your returns. You need to return a select group of member from your input array.

So, you create a new empty array, and then write an each/do that only shovels members of the input array into the new array that meet certain criteria. Then you return the new array.

new_array = []
array.each do |x|
	new_array << x if x %3 == 0
end

Guess what! That's the long version of #select! Exciting!

array.select {|x| x % 3 == 0}

The More You Know...

Enumerators can help make your code dry, but they also end up being super powerful. One of these days, I'd like to write more on chaining enumerators. Stay tuned!

comments powered by Disqus