While learning to code, enumerable methods have proven themselves time and again to be invaluable. Often I will find myself writing 5-6 lines of code for a method and realizing it could have all been completed by a simple, one or two word method. Im going to explore how some of them that might not be as well known, at least I haven't used them often yet.
.all?
This enumerable method takes a block and for each object passed in, assesses if it is true or false. If all the objects are true the return value will be true. If even one of the objects returns false or nil, the method will return false. If no block is given .all? provides one that would read {|object| object} so that it can look at each element in the array or hash being acted upon.
given the following code:
Here we see that the arrays that have any odd number in them return false, but the array with only evens included returns true!
.each_with_object
the .each_with_object enumerable method is a bit complicated to understand and the ruby documentation includes only a short description of what this elusive method can do.
If you want to solve a problem like the one below in which we would like to return a hash where the key is the original object and the value is the new object after being acted on by the block.
.each_with_object offers a way to do this without sandwiching
The tricky bit for this method is that it returns the original object given, just as .each does.
I believe what this means is that the original value is not altered by the method, it stays the same, but is used to create a new object based on the original and the block. The output can include both of these objects.
.take / .take_while
These two methods are somewhat specific, but can certainly be useful to know of! The .take method is given an argument of a fixnum and then will take that number of elements from the start of the enumerable that the method is called on.
The .take_while method takes a block and evaluates if the return value is true or false. Once it hits a false value it stops iterating over the element and will return all the elements from the enumerator that came before the false.
No comments:
Post a Comment