Ruby - Module Enumerable

Introduction

Ruby Enumerable module supplies about 20 useful counting- and iteration-related methods, including collect, detect, find, find_all, include?, max, min, select, sort, and to_a.

All of these use Array's each method to do their jobs.

If your class can implement an each method, you can include Enumerable, and get all those methods in your own class!

Some examples of the methods provided by Enumerable:

[1,2,3,4].collect { |i| i.to_s + "x" } # ["1x", "2x", "3x", "4x"] 
[1,2,3,4].detect { |i| i.between?(2,3) } #2 
[1,2,3,4].select { |i| i.between?(2,3) } #[2,3] 
[4,1,3,2].sort # [1,2,3,4] 
[1,2,3,4].max # 4 
[1,2,3,4].min # 1 

Related Topics