Class: Array

Inherits:
Object show all
Defined in:
lib/hash-utils/array.rb

Overview

Array extension.

Instance Method Summary collapse

Instance Method Details

#merge!(*arrays) ⇒ Array

Merges arrays in place. It seems to be rather unuseful, but it’s intended for special cases, for example joining arrays while constructing.

An example (underlying object is extended array):

def initialize(array)
    self += array       # impossible, will fail
    self.merge! array   # possible, of sure
end

Parameters:

  • arrays (Array)

    array for merge-in

Returns:

Since:

  • 0.10.0



91
92
93
94
95
# File 'lib/hash-utils/array.rb', line 91

def merge!(*arrays)
    arrays.flatten!(1)
    arrays.each { |i| self << i }
    self
end

#remove!(&block) ⇒ Array

Moves selected values outside the array, so returns them.

Works similar to Hash#reject!, but returns removed items instead of remaining items.

Parameters:

  • block (Proc)

    selecting block

Returns:

  • (Array)

    removed values

Since:

  • 0.3.0



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/hash-utils/array.rb', line 21

def remove!(&block)
    result = [ ]
    self.reject! do |v|
        if block.call(v)
            result << v
            true
        else
            false
        end
    end
    
    return result
end

#to_h(mode = nil) ⇒ Hash

Returns new hash.

Examples:

Equivalent calls

[["aa", "bb"], ["bb", "aa"]].to_h
["aa", "bb", "bb", "aa"].to_h(:flat)

Parameters:

  • mode (Symbol) (defaults to: nil)

    flat mode switch, can be :flat or nil

Returns:

  • (Hash)

    new hash

See Also:

Since:

  • 0.4.0



67
68
69
70
71
72
73
# File 'lib/hash-utils/array.rb', line 67

def to_h(mode = nil)
		if mode == :flat
			Hash[*self]
		else
			Hash[self]
		end
end