Using String#split method with block

I’m going to talk about a new feature that comes with the Ruby 2.6 version.

The split method of dividing a text according by characters or regex., allows you to create arrays.

We can use split method with block. This method will make our code cleaner on some issues. At the same time memory usage will be reduced.

For example:

shopping_items = 'order,cart,payment'

shopping_items.split(',')
=> ["order", "cart", "payment"]

important_items = shopping_items.select { |i| item_important?(i) }
=> ["order", "payment"]

We created an intermediate array and filtered the shopping_items using select method.

With block:

important_items = []

shopping_items = 'order,cart,payment'

shopping_items.split(',') { |i| important_items << i if item_important?(i) }
=> "order,cart,payment"

important_items
=> ["order", "payment"]

When use split with block, it returns the string and does not create an array. So we filtered our shopping_items without using an intermediate array.