Enumerable and Comparable in Ruby

3

I read the Ruby documentation where it talks about the Enumerable and Comparable modules, but I did not quite understand what they do. Could someone give me some examples where I use them in my classes?

    
asked by anonymous 28.04.2018 / 05:26

1 answer

3

TLDR : Enumerable is responsible for searching and sorting and Comparable for exposing sorting rules ( > , < , >= , <= ) of the enumeration items.

The relationship between Enumerable and Comparable is implied. Let's go to the concepts:

Mixin Enumerable is used in collections that need search and sort methods . The Array class of Ruby, for example, extends the Enumerable module.

[:debito, :credito, :boleto].include? :dinheiro
=> false

In the example above, I used the Enumerable#include? , available through class Array .

In addition to the ability to search, Enumerable also sorts. The problem is: to order, you need comparators like bigger, smaller and equal.

Enumerable sorting methods require items in the collection to extend or implement Comparable , or have a method of name <=> and return 1 , 0 or -1 .

So this is how you can do this kind of operation:

nomes = ['João', 'Maria', 'Carlos']
nomes.max
=> 'Maria'
    
28.04.2018 / 16:00