Module: Lab42::List::ClassMethods

Included in:
Lab42::List
Defined in:
lib/lab42/list/class_methods.rb

Instance Method Summary collapse

Instance Method Details

#cons(element, list) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
# File 'lib/lab42/list/class_methods.rb', line 6

def cons(element, list)
  raise ArgumentError, "list needs to be a list instance" unless list?(list)

  allocate.tap do |o|
    o.instance_variable_set("@car", element)
    o.instance_variable_set("@cdr", list)
    o.instance_variable_set("@length", list.length.succ)
    o.freeze
  end
end

#each(subject, &blk) ⇒ Object



17
18
19
20
21
22
# File 'lib/lab42/list/class_methods.rb', line 17

def each(subject, &blk)
  unless subject.empty?
    blk.(subject.car)
    each(subject.cdr, &blk)
  end
end

#list?(subject) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/lab42/list/class_methods.rb', line 24

def list?(subject)
  self === subject || Nil == subject
end

#new(*elements) ⇒ Object



28
29
30
31
32
# File 'lib/lab42/list/class_methods.rb', line 28

def new(*elements)
  elements.reverse.inject(Nil) do |list, element|
    cons(element, list)
  end
end