Module: Enumerable

Included in:
Hamster::Enumerable
Defined in:
lib/hamster/core_ext/enumerable.rb

Overview

Ruby's built-in Enumerable module.

Instance Method Summary collapse

Instance Method Details

#to_listList

Return a new Hamster::List populated with the items in this Enumerable object.

Returns:

  • (List)

8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/hamster/core_ext/enumerable.rb', line 8

def to_list
  # use destructive operations to build up a new list, like Common Lisp's NCONC
  # this is a very fast way to build up a linked list
  list = tail = Hamster::Cons.allocate
  each do |item|
    new_node = Hamster::Cons.allocate
    new_node.instance_variable_set(:@head, item)
    tail.instance_variable_set(:@tail, new_node)
    tail = new_node
  end
  tail.instance_variable_set(:@tail, Hamster::EmptyList)
  list.tail
end