module ArrayExt

Add the methods to the Array Class

Public Instance Methods

array_to_hash(init_val = 0) click to toggle source

Generate a hash with the given array elements as keys and 'init_value' as value

# File lib/array.rb, line 37
def array_to_hash(init_val = 0)
  h = {}
  self.each {|x| h.merge!(x => init_val) unless x.nil? }
  return h
end
avg(attribute = nil) click to toggle source

Get avg. value from, either from numeric values or from values from a object included in array

# File lib/array.rb, line 17
def avg(attribute = nil)
  value = self
  if attribute.nil?
    value.delete(nil)
    value = self.map {|r| r.to_f }
  else
    value = self
    # Bei fehlerhaften attribute wird nil gespeichert
    value = value.map {|r| r.send(attribute.to_sym).to_f rescue nil}
    # Leere Werte löschen
    value.delete(nil)
  end
  # Divide by zero ausschließen
  value.size == 0 ? size = 1 : size = value.size
  value.sum / size
end
count_for(item) click to toggle source

check the number of items included in the array

# File lib/array.rb, line 103
def count_for(item)
  count = 0
  self.each {|x| count += 1 if x == item}
  return count
end
even_values() click to toggle source
# File lib/array.rb, line 279
def even_values
  self.values_at(* self.each_index.select {|i| i.even?})
end
except(*args) click to toggle source

like except for hash

# File lib/array.rb, line 129
def except(*args)
  excluded = *args
  return self - excluded
end
fill_with_sth(sth, size) click to toggle source

Untested / deprecated functions below, should be moved somewhere else!

Ignore these functions, there are neither tested nor documented, use them for fun if you like but dont ask me ;-)
# File lib/array.rb, line 175
def fill_with_sth(sth, size)
  ary_length = self.size
  diff = size - ary_length
  if diff > 0
    pop = Array.new(diff){|i| sth}
    new_ary = pop.push(self).flatten!
    return new_ary
  else
    return self
  end
end
interpolate(filtered_value = nil, options = {}) click to toggle source
# File lib/array.rb, line 200
def interpolate(filtered_value = nil, options = {})
  begin

    int_start_value = nil
    int_end_value   = nil
    int_from        = 0
    int_to          = 0
    int_steps       = 0

    array_with_interpolation = []

    self.each_with_index do |x,i|
      if i > 0
        if x != filtered_value
          # Wenn der letze ein fehler war ist die strecke zuende
          if self[i-1] == filtered_value

            if i-1 == 0
              # Berechnung anstieg der linearfunktion zwischen Start-und Endpunkt
              #
              m = (self[i+1]-x)

              array_with_interpolation[0] = x-m
              array_with_interpolation << x

            else
              int_end_value = x
              int_to        = i

              # Berechnung anstieg der linearfunktion zwischen Start-und Endpunkt
              m = (int_end_value-int_start_value).fdiv((int_to-int_from))

              # Fülle fehlende werte mit werten (y = mx + b)
              int_steps.times {|mi| array_with_interpolation << (int_start_value+((mi+1)*m)) }
              array_with_interpolation << int_end_value

              # Reset all values
              int_start_value = int_end_value
              int_end_value   = nil
              int_from        = 0
              int_to          = 0
              int_steps       = 0
              puts array_with_interpolation.inspect
            end
          else
            int_start_value = x
            array_with_interpolation << x
          end
        # Wenn letzer wert fehlerhaft
        elsif i == self.size-1 && x == filtered_value
          # Berechnung anstieg der linearfunktion zwischen Start-und Endpunkt
          # Berechnung über gesamtes array
          m = (array_with_interpolation.last-array_with_interpolation.first).fdiv(array_with_interpolation.size-1)
          array_with_interpolation << (array_with_interpolation.last+m)
        else
          int_steps += 1
          int_from = i-int_steps
        end

      else
        int_start_value = x
        array_with_interpolation << x
      end

    end

    return array_with_interpolation
  rescue
    puts "WARNING: Interpolation not possible!".red
    return self
  end

end
isec(b) click to toggle source

Schnittmenge / Intersection zwischen 2 Arrays

# File lib/array.rb, line 123
def isec(b)
  raise ArgumentError, "#{b.inspect} is not an array" if !b.is_a?(Array)
  (self- (self-b))
end
json_labels() click to toggle source

Generiert einen JSON-String aus einem Array mit Werten

# File lib/array.rb, line 189
def json_labels
  json = "["
  self.each_with_index {|l,i| json << '{"id": "%s", "text": "%s"}' % [i, l] ; json << "," unless i+1 == self.size}
  json << "]"
end
next(val, options = {}) click to toggle source

return the item after the given val in array returns val if no item found or val is not included toggle :cycle => true to continue search at beginn of array if end is reached

# File lib/array.rb, line 113
def next(val, options = {})
  i = self.index(val)
  return val if i.nil?

  i == self.size-1 ?
    (options[:cycle] == true ? self.first : val) : self[i+1]
end
odd_values() click to toggle source
# File lib/array.rb, line 275
def odd_values
  self.values_at(* self.each_index.select {|i| i.odd?})
end
seperate(n = 8) click to toggle source

break array into n arrays

# File lib/array.rb, line 135
def seperate(n = 8)
  f = n
  aks_size  = self.size
  rest      = aks_size % f

  stack = ((aks_size - rest) / f)

  arrays = (1..f).to_a

  arrays.map! {|i| self.first(stack*i).last(stack) }
  arrays[-1] += self.last(rest) if rest != 0
  #arrays.last.pop if (arrays.last.last.empty? || arrays.last.last.blank?)
  return arrays
end
stack(n = 4) click to toggle source

[1,2,3,5,6,7].stack(2)

will return [[1, 2], [3, 5], [6, 7]]
# File lib/array.rb, line 152
def stack(n = 4)
  arr = []
  i = (self.size.to_f/n).ceil
  i.times do |x|
    arr << self[x*n..(((x+1)*n)-1)]
  end
  return arr
end
sum(identity = 0, &block) click to toggle source

Use sum from Activesupport Sum is not a default in Ruby

# File lib/array.rb, line 7
def sum(identity = 0, &block)
  if block_given?
    map(&block).sum(identity)
  else
    inject { |sum, element| sum + element } || identity
  end
end
sum_with_attribute(arg, opt =nil) click to toggle source

Sum up an array of objects with given attirbute Attributes can be given as symbol (:my_value will return obj.my_value) or as string (“user.my_value” will return my_value from user object which belongs to object in array) also, options could be passed, which could be *args or options hash

# File lib/array.rb, line 75
def sum_with_attribute(arg, opt =nil)
  if arg.nil?
    return self.compact.sum
  else
    values = []
    if arg.is_a?(Symbol)
      self.map {|i| ((opt.nil? ? i.send(arg) : i.send(arg, opt)) rescue 0) }.sum
    elsif arg.is_a?(String)
      self.each do |v|
        tag_methods = arg.split(".")
        tagx = v.send(tag_methods[0])
        tag_methods[1..-1].each do |x|
          # Use options if last method in chain called
          if tag_methods[1..-1].last == x && !opt.nil?
            tagx = tagx.send(x,opt)
          else
            tagx = tagx.send(x)
          end
        end
        values << tagx
      end
      return values.compact.sum
    end
  end
end
to_sql() click to toggle source

Prepare array for use with mysql IN operator

# File lib/array.rb, line 163
def to_sql
  return "(NULL)" if self.empty?
  if self.first.is_a?(Numeric)
    return "(#{self.compact.join(',')})"
  else
    return "(#{self.map{|i| "'#{i.to_s}'"}.join(',')})"
  end
end
to_structured_hash(attribute, options = {}) click to toggle source
# File lib/array.rb, line 44
def to_structured_hash(attribute, options = {})
  data = {}

  self.each do |item|
    if attribute.is_a?(Symbol) && options[:load_from_hash] != true
      key = item.send(attribute) rescue ""
    elsif attribute.is_a?(Symbol) && options[:load_from_hash] == true
      key = item[attribute] rescue ""
    elsif attribute.is_a?(String)
      attribute_methods = attribute.split(".")
      key = item.send(attribute_methods[0])
      attribute_methods[1..-1].each do |x|
        key = key.send(x) rescue ""
      end
    end

    if data[key].nil?
      data.merge!(key => [item])
    else
      data[key] << item
    end
  end

  return data
end
to_text(sep = "<br />") click to toggle source
# File lib/array.rb, line 195
def to_text(sep = "<br />")
  self.join(sep)
end