1. Syntactical Shortcuts for Iterations
When you need to apply a method to all items within an Enumerable
, instead of creating a block syntax with a local variable, you can prepend an &
before the Symbol
that represents the method name and pass it to the iteration method as an argument. This works for all functions that do not take an argument.
1 2 3 4 5 |
|
These shortcuts work because calling Symbol#to_proc
returns a proc that responds to the symbol’s method. So the :capitalize
symbol is first converted to a proc, and then to a block.
Similarly, you can pass the Symbol
for a function into #inject
and it will sequentially apply the method to items. This method needs to take one argument, which in this case will be num
and it gets sent to the collector sum
.
1 2 3 4 5 |
|
2. Set Intersection for an Array
There’s an easy way to get the intersection, or set of common elements, of two Array
s. By applying the &
operator to one Array
and passing the other as an argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
3. Ignoring Arguments and Return Values
In cases where argument variables need to be set in order to receive values, you can end up with verbose code becaues unused arguments are specified. By using the _
(underscore) as an argument, it visually hides some of the received values. Also, when defining _
multiple times it will not raise a SyntaxError
unlike any other variable name.
1 2 3 4 5 6 7 |
|
1 2 3 4 5 |
|
4. Autovivification
Hash.new
can take a block that is run when a non-existing key is accessed. The code snipped below ensures that a Hash
with infinite sub-Hash nesting gets created when accessing an arbitrary depth of non-existing keys.
1 2 3 4 |
|
5. Advanced Text Interpolation
When interpolating variable values into a string, the variables are commonly placed within the delimited text. The %
allows us to replace the character string %s
within the text with items from an array.
1 2 3 4 5 |
|
6. Lazy Loading
We all like to be lazy sometimes. Starting in Ruby 2.0, we can now let Enumerable
objects be lazy too. All this means is that the result of the enumerable function will not get evaluated until you tell it to.
1 2 3 4 5 6 7 |
|
The behavior in this example doesn’t really show the full potential of #lazy
. Imagine that you have an operation that you want to apply to a collection, however, the contents of the given collection are dynamically changing. Using #lazy
keeps the enumerator updated with the latest state of the collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
7. Counting A Subset
You may use #count
on a daily basis, but did you know that you can specify a parameter to the method call? It will return the number of occurrances of that particular value.
1 2 3 |
|
If you though that was cool, then hold on to your pants. When you add a block that evaluates a condition for each item in the collection, you can add logic regarding which items you want to count. If the block return true
the item gets counted.
1 2 |
|