Today I read Ruby's magical Enumerable module from AppSignal. It clearly explains the subject. And It gives a short code for linked list, I like it.
class LinkedList def initialize(head, tail = nil) @head, @tail = head, tail end def <<(item) LinkedList.new(item, self) end def inspect [@head, @tail].inspect end end
irb> LinkedList.new(73) << 12 << 42 => [42, [12, [73, nil]]]
And then with a each method and a include, You can make it Enumerable.
class LinkedList include Enumerable def initialize(head, tail = nil) @head, @tail = head, tail end def <<(item) LinkedList.new(item, self) end def inspect [@head, @tail].inspect end def each(&block) block.call(@head) @tail.each(&block) if @tail end end
irb> list = LinkedList.new(73) << 12 << 42 => [42, [12, [73, nil]]] irb> list.count => 3 irb> list.max => 73 irb> list.map { |item| item * item } => [1764, 144, 5329] irb> list.select(&:even?) => [42, 12]
I like the gradually way of explaining code. And you?
Top comments (0)