123456789_123456789_123456789_123456789_123456789_

Class: Insertion

Relationships & Source Files
Inherits: Object
Defined in: lib/yard/core_ext/insertion.rb

Overview

The Insertion class inserts a value before or after another value in a list.

Examples:

Insertion.new([1, 2, 3], 4).before(3) # => [1, 2, 4, 3]

Class Method Summary

Instance Method Summary

Constructor Details

.new(list, value) ⇒ Insertion

Creates an insertion object on a list with a value to be inserted. To finalize the insertion, call #before or #after on the object.

Parameters:

  • list (Array)

    the list to perform the insertion on

  • value (Object)

    the value to insert

[ GitHub ]

  
# File 'lib/yard/core_ext/insertion.rb', line 14

def initialize(list, value)
  @list = list
  @values = (Array === value ? value : [value])
end

Instance Method Details

#after(val, recursive = false)

Inserts the value after val.

Examples:

If subsections are ignored

Insertion.new([1, [2], 3], :X).after(1) # => [1, [2], :X, 3]

Parameters:

  • val (Object)

    the object the value will be inserted after

  • recursive (Boolean) (defaults to: false)

    look inside sublists

[ GitHub ]

  
# File 'lib/yard/core_ext/insertion.rb', line 30

def after(val, recursive = false) insertion(val, 1, recursive) end

#after_any(val)

Alias for #after with recursive set to true

Since:

  • 0.6.0

[ GitHub ]

  
# File 'lib/yard/core_ext/insertion.rb', line 38

def after_any(val) insertion(val, 1, true) end

#before(val, recursive = false)

Inserts the value before val

Parameters:

  • val (Object)

    the object the value will be inserted before

  • recursive (Boolean) (defaults to: false)

    look inside sublists

[ GitHub ]

  
# File 'lib/yard/core_ext/insertion.rb', line 22

def before(val, recursive = false) insertion(val, 0, recursive) end

#before_any(val)

Alias for #before with recursive set to true

Since:

  • 0.6.0

[ GitHub ]

  
# File 'lib/yard/core_ext/insertion.rb', line 34

def before_any(val) insertion(val, 0, true) end

#insertion(val, rel, recursive = false, list = @list) (private)

This method performs the actual insertion

Parameters:

  • val (Object)

    the value to insert

  • rel (Fixnum)

    the relative index (0 or 1) of where the object should be placed

  • recursive (Boolean) (defaults to: false)

    look inside sublists

  • list (Array) (defaults to: @list)

    the list to place objects into

[ GitHub ]

  
# File 'lib/yard/core_ext/insertion.rb', line 49

def insertion(val, rel, recursive = false, list = @list)
  if recursive
    list.each do |item|
      next unless item.is_a?(Array)
      tmp = item.dup
      insertion(val, rel, recursive, item)
      return(list) unless item == tmp
    end
  end

  index = list.index(val)
  list[index + rel, 0] = @values if index
  list
end