class Array

Public Instance Methods

array % other_array → aString click to toggle source
array % str → aString

Format–Uses the first string in array for which the corresponding combination of other_array does not contain blank elements as a format specification, and returns the result of applying it to that combination (cf. String#%). Returns an empty string if other_array is empty.

Applies to string argument accordingly: First string in array applied to str; empty string if str is empty.

# File lib/nuggets/array/format.rb, line 42
def %(args)
  opts = { sep: ', ' }
  opts.update(pop) if last.is_a?(::Hash)

  default = lambda { |n| ['%s'] * n * opts[:sep] }

  case args
    when ::String
      return (first || default[1]) % args unless
        args.nil? || args.empty?
    when ::Array
      i = 0
      [*args].comb { |x|
        return (self[i] || default[x.size]) % x unless
          x.empty? || x.any? { |y| y.nil? || y.empty? }

        i += 1
      }
  end

  ''
end
ascending? → +true+ or +false+ click to toggle source

Check whether array is (strictly) ascending.

# File lib/nuggets/array/monotone.rb, line 51
def ascending?(strict = false)
  monotone?(strict ? :< : :<=)
end
Also aliased as: increasing?
comb(n, ...) → new_array click to toggle source
comb(n, ...) { |combination| ... } → new_array

Returns an array of arrays of each possible n-combination of array for each given n. If a block is given, each combination is yielded to it. Based on <blade.nagaokaut.ac.jp/~sinara/ruby/math/combinatorics/array-comb.rb>.

# File lib/nuggets/array/combination.rb, line 36
def comb(*sizes)
  # If no sizes are given, produce all!
  sizes = (0..size).to_a.reverse if sizes.empty?

  combinations, collect_and_yield = [], lambda { |combination|
    yield combination if block_given?
    combinations << combination
  }

  sizes.each { |n|
    case n
      when 0        # Short-cut (breaks recursion)
        collect_and_yield[[]]
      when 1..size  # Ignore out-of-range values
        self[1..-1].comb(n - 1) { |combination|
          collect_and_yield[combination.unshift(first)]
        }
        self[1..-1].comb(n) { |combination|
          collect_and_yield[combination]
        }
    end
  }

  combinations
end
decreasing?(strict = false)
Alias for: descending?
descending? → +true+ or +false+ click to toggle source

Check whether array is (strictly) descending.

# File lib/nuggets/array/monotone.rb, line 69
def descending?(strict = false)
  monotone?(strict ? :> : :>=)
end
Also aliased as: decreasing?
flatten_once → new_array click to toggle source

Flatten array by one level only. Pretty straight-forward port of David Alan Black's flattenx C implementation (though much slower, of course ;-).

# File lib/nuggets/array/flatten_once.rb, line 34
def flatten_once
  flat = []

  each { |element|
    if element.is_a?(::Array)
      flat += element
    else
      flat << element
    end
  }

  flat
end
flatten_once! → array click to toggle source

Destructive version of flatten_once.

# File lib/nuggets/array/flatten_once.rb, line 52
def flatten_once!
  replace(flatten_once)
end
in_order(*ordered) → new_array click to toggle source

Force order, but ignore non-existing and keep remaining.

Examples:

[:created_at, :email, :login, :updated_at].in_order(:login, :email)    #=> [:login, :email, :created_at, :updated_at]
[:created_at, :email, :login, :updated_at].in_order(:email, :address)  #=> [:email, :created_at, :login, :updated_at]
# File lib/nuggets/array/in_order.rb, line 37
def in_order(*ordered)
  ordered &= self
  ordered + (self - ordered)
end
in_order!(*ordered) → array click to toggle source

Destructive version of in_order.

# File lib/nuggets/array/in_order.rb, line 46
def in_order!(*ordered)
  replace(in_order(*ordered))
end
increasing?(strict = false)
Alias for: ascending?
monotone?(operator) → +true+ or +false+ click to toggle source

Check whether array is monotone according to operator.

# File lib/nuggets/array/monotone.rb, line 33
def monotone?(operator = nil)
  if [nil, true, false].include?(operator)
    ascending?(operator) || descending?(operator)
  else
    inject { |a, b|
      return false unless a.send(operator, b)
      b
    }

    true
  end
end
Also aliased as: monotonic?
monotonic?(operator = nil)
Alias for: monotone?
only → anObject click to toggle source
only(+true+) → anObject

Returns the only element of array. Raises an IndexError if array's size is not 1, unless parameter true is passed.

Idea stolen from Gavin Sinclair's Ruby Extensions Project.

# File lib/nuggets/array/only.rb, line 37
def only(relax = size == 1)
  relax ? first : raise(::IndexError, 'not a single-element array')
end
rand → anItem click to toggle source

Randomly pick an item from array.

# File lib/nuggets/array/rand.rb, line 33
def rand
  at(::Kernel.rand(size))
end
shuffle → new_array click to toggle source

Shuffles array in random order. Select a different shuffling algorithm: Array.send(:alias_method, :shuffle, :shuffle_kfy).

# File lib/nuggets/array/shuffle.rb, line 34
def shuffle
  sort_by { ::Kernel.rand }
end
shuffle! → array click to toggle source

Destructive version of shuffle.

# File lib/nuggets/array/shuffle.rb, line 58
def shuffle!
  replace shuffle
end
shuffle_kfy → new_array click to toggle source

Non-destructive version of shuffle_kfy!.

# File lib/nuggets/array/shuffle.rb, line 50
def shuffle_kfy
  dup.shuffle_kfy!
end
shuffle_kfy! → array click to toggle source

Shuffles array in random order using the Knuth-Fisher-Yates algorithm.

# File lib/nuggets/array/shuffle.rb, line 79
def shuffle_kfy!
  (length - 1).downto(0) { |i|
    n = rand(i + 1)
    self[n], self[i] = self[i], self[n]
  }

  self
end
shuffle_knuth → new_array click to toggle source

Non-destructive version of shuffle_knuth!.

# File lib/nuggets/array/shuffle.rb, line 42
def shuffle_knuth
  dup.shuffle_knuth!
end
shuffle_knuth! → array click to toggle source

Shuffles array in random order using Knuth's algorithm.

# File lib/nuggets/array/shuffle.rb, line 66
def shuffle_knuth!
  0.upto(length - 2) { |i|
    n = i + rand(length - i)
    self[i], self[n] = self[n], self[i]
  }

  self
end
sort_by_dotted_decimal() click to toggle source
# File lib/nuggets/dotted_decimal.rb, line 55
def sort_by_dotted_decimal
  sort_by { |i| i.split('.').map { |j| j.to_i } }
end
strictly_ascending? → +true+ or +false+ click to toggle source

Check whether array is strictly ascending.

# File lib/nuggets/array/monotone.rb, line 60
def strictly_ascending?
  ascending?(true)
end
Also aliased as: strictly_increasing?
strictly_decreasing?()
strictly_descending? → +true+ or +false+ click to toggle source

Check whether array is strictly descending.

# File lib/nuggets/array/monotone.rb, line 78
def strictly_descending?
  descending?(true)
end
Also aliased as: strictly_decreasing?
strictly_increasing?()
Alias for: strictly_ascending?
to_h(value = default = true)
Alias for: to_hash
to_hash → aHash click to toggle source
to_hash(value) → aHash
to_hash { |element| ... } → aHash

If neither value nor block is given, converts array, taken as an array of key/value pairs, into a hash, preserving sub-arrays (Thus: hash.to_a.to_h == hash). Otherwise, maps each element of array to value or the result of the block.

Examples:

[[0, 0], [1, [2, 3]]].to_h  #=> { 0 => 0, 1 => [2, 3] }
%w[a b c d].to_h            #=> { "a" => "b", "c" => "d" }
%w[a b c d].to_h(1)         #=> { "a" => 1, "b" => 1, "c" => 1, "d" => 1 }
%w[a b].to_h { |e| e * 2 }  #=> { "a" => "aa", "b" => "bb" }
# File lib/nuggets/array/to_hash.rb, line 46
def to_hash(value = default = true)
  hash = {}

  if block_given?
    raise ::ArgumentError, 'both block and value argument given' unless default

    each { |element| hash[element] = yield element }
  elsif !default
    each { |element| hash[element] = value }
  else
    return ::Hash[*flatten_once]
  end

  hash
end
Also aliased as: to_h