What is the relationship between Array and Enumerable?

Array

does not have sort_by

; Enumerable

has it. How it works?

%w[aa aaaa aaa].sort_by{|item| item.length} #=> ['aa','aaa','aaaa']

      

Shouldn't that throw an error, for example undefined method sort_by

? What is the relationship between Array

and Enumerable

?

+3


source to share


3 answers


The class Array

includes a module Enumerable

. You can see this in the documentation on the left under Included Modules.



+3


source


Enumerable

mixes up with class Array

: all methods defined by Enumerable are available for Ruby arrays.



Array.ancestors # => [Array, Enumerable, Object, Kernel, BasicObject]

+2


source


This is called inheritance. If the method is not found in the object class, Ruby lifts up the ancestor chain until it finds one.

Array

inherits from Enumerable

(more precisely, it mixes in Enumerable

, which is a form of inheritance).

0


source







All Articles