The Ruby core team shipped an awesome new version – Ruby 2.2.0 – on Christmas day. What an awesome gift! Notable enhancements include both incremental garbage and symbol garbage collection.
Both of these together should provide noticeable improvements to memory usage and will allow the Rails core team to “shed a lot of weight” with regards to user input and how strings are handled.
Let’s try out a couple of the new features, namely Enumerable#slice_after
and
Enumerable#slice_when
Install Ruby 2.2.0
I really enjoy ruby-install, so that’s how I installed the new version on my system. If you’re not already using it, I highly recommend it.
Once that’s done downloading and compiling, I simply use chruby to switch to the new version.
Enumerable#slice_after
#slice_after
is a counterpart to the already existing #slice_before
This method lets you split an enumerator with each item being grouped into a new chunk when the result of the block is true. So in the example below, you can see a new chunk is created after each odd number.
Enumerable#slice_when
This method allows you to slice the enumerable by comparing adjacent elements. When the block is true a new chunk is created. Say you have an array of numbers and you want to list them where subsequent numbers are grouped into ranges, like “1, 5, 9-12, 15” for example.
Let me know what you like about this release. Go forth and be productive!
Sources and Info
- Ruby 2.2 release announcement
- Enumerable#slice_after – documentation, discussion
- Enumerable#slice_when – documentation, discussion