Class: Jinx::Flattener

Inherits:
Object show all
Includes:
Enumerable, Collection
Defined in:
lib/jinx/helpers/flattener.rb

Overview

A Flattener applies a given block to flattened collection content.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Enumerable

#enumerate, #pp_s, #pretty_print, #pretty_print_cycle, #qp, #to_enum, #transitive_closure

Methods included from Collection

#compact, #compact_map, #detect_value, #detect_with_value, #difference, #empty?, #filter, #first, #flatten, #hashify, #intersect, #join, #last, #partial_sort, #partial_sort!, #partial_sort_by, #size, #to_compact_hash, #to_compact_hash_with_index, #to_series, #transform, #union

Constructor Details

#initialize(obj) ⇒ Flattener

Initializes a new Flattener on the given object.

Parameters:

  • obj

    the Enumerable or non-collection object



16
17
18
# File 'lib/jinx/helpers/flattener.rb', line 16

def initialize(obj)
  @base = obj
end

Class Method Details

.on(obj, &block) ⇒ Object

Visits the enumerated items in the given object’s flattened content. The given block is called on the base itself if the base is neither nil nor a Enumerable. If the base object is nil or empty, then this method is a no-op and returns nil.



9
10
11
# File 'lib/jinx/helpers/flattener.rb', line 9

def self.on(obj, &block)
  obj.collection? ? obj.each { |item| on(item, &block) } : yield(obj) unless obj.nil?
end

Instance Method Details

#each(&block) ⇒ Object

Calls the the given block on this Flattener’s flattened content. If the base object is a collection, then the block is called on the flattened content. If the base object is nil, then this method is a no-op. If the base object is neither nil nor a collection, then the block given to this method is called on the base object itself.

Examples:

Flattener.new(nil).each { |n| print n } #=>
Flattener.new(1).each { |n| print n } #=> 1
Flattener.new([1, [2, 3]]).each { |n| print n } #=> 123


30
31
32
# File 'lib/jinx/helpers/flattener.rb', line 30

def each(&block)
  Flattener.on(@base, &block)
end

#to_sObject



34
35
36
# File 'lib/jinx/helpers/flattener.rb', line 34

def to_s
  to_a.to_s
end