3
I read the Ruby documentation about the modules Enumerable
and Comparable
, but I didn’t really understand what they do. Could someone give me some examples where I use them in my classes?
3
I read the Ruby documentation about the modules Enumerable
and Comparable
, but I didn’t really understand what they do. Could someone give me some examples where I use them in my classes?
3
DRT: the Enumerable
is responsible for seeking and ordering and the Comparable
by setting out the ordination rules (>
, <
, >=
, <=
) of the items of the enumeration.
The relationship between the Enumerable
and the Comparable
is implicit. Let’s go to the concepts:
The mixin Enumerable
is used in collections that need search and sort methods. The class Array
, Ruby, for example, extends the module Enumerable
.
[:debito, :credito, :boleto].include? :dinheiro
=> false
In the above example, I used the method Enumerable#include?
, available through the class Array
.
In addition to the ability to search, the Enumerable
also sorts. The problem is: to sort, one needs comparators as larger, smaller and equal.
The ordering methods of Enumerable
need the collection items to extend or implement the Comparable
, or has a name method <=>
and return 1
, 0
or -1
.
So that’s how you can do this kind of operation:
nomes = ['João', 'Maria', 'Carlos']
nomes.max
=> 'Maria'
Browser other questions tagged ruby
You are not signed in. Login or sign up in order to post.
Would you have an example of how to implement in my classes? .
– João Pontes