6 advanced Ruby loops

Tram Ho

Ruby is a language with the principles of “optimized for developers”. It’s an easy-to-read, easy-to-write, integrated, template and prototype language, among other benefits. One of its best features is the provision of helper methods for many commonly used methods. Repeat, sort, filter, transform, and other methods all have many built-in helper helpers in the language (can be listed in the module).

You can focus more on your logic and less on writing the built-in repetitive helper helper. What makes the code easier to read.

These help methods abstract the details of how iteration occurs and provide its own logic. Since code is read much more frequently than it is written, it also makes code more efficient.

I want to take a look at some of the lesser known Ruby loops. These will make the code less verbose, easier to read, and faster to write:

Note: All of these methods will work for both arrays and hashes. Both are considered listed.

map

Useful for creating an array from an existing array and applying certain logic to each element. For example, squaring each value in an array. So instead of using each element to iterate over and insert the result into another array, you can just use map.

each_with_object

Useful for creating an object by iterating over a metric. For example, want to create a hashes from an array? Or a Person object from a given hashes?

each_with_index

Useful when, in addition to looping through a metric, you also need to use an index. Example: Need to record the current index we are working with?

partition

Imagine you can divide an array into two arrays, based on a condition. You can do exactly that with the partition:

select / reject

select iterates over an enumeration and returns only the items returned for the given block. deny the same actions but on the contrary, it returns actions that do not satisfy the condition:

For arrays, select and reject is available! : select! and reject !, will modify the given enumeration type.

any? / all?

any? Tests if at least one element in an enumeration corresponds to a condition. all? Verify that all elements match the condition.

Share the news now

Source : Viblo