Skip to content
Justice Tech School

Enumerable and each_slice

Classes with each can include Enumerable to get map, select, sort and more.

Example
class Bag
  include Enumerable
  def initialize(*i) = @i = i
  def each(&b) = @i.each(&b)
end
b = Bag.new(3, 1, 2)
p b.sort, b.map { |x| x * 2 }, b.min, b.include?(2)
p (1..7).each_slice(3).to_a, (1..4).each_cons(2).to_a

Result

[1, 2, 3]
[6, 2, 4]
1
true
[[1, 2, 3], [4, 5, 6], [7]]
[[1, 2], [2, 3], [3, 4]]

Exercise

Mixin for collections.

include 

Quiz Test

What method must you define?

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