Skip to content
Justice Tech School

Enumerable and Lazy

Any class that defines each and includes Enumerable gets map, select, sort and more. lazy delays work so long or infinite sequences are efficient.

Example
class Countdown
  include Enumerable
  def initialize(n) = @n = n
  def each
    @n.downto(1) { |i| yield i }
  end
end
puts Countdown.new(5).select(&:odd?).inspect
puts (1..Float::INFINITY).lazy.map { |x| x * 2 }.select { |x| x % 3 == 0 }.first(3).inspect

Result

[5, 3, 1]
[6, 12, 18]

Exercise

Mix in the module.

include 

Quiz Test

What must a class define to be Enumerable?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.