Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/theusual/array.rb

Instance Method Summary collapse

Instance Method Details

#avgObject Also known as: average, mean



10
11
12
13
14
15
# File 'lib/theusual/array.rb', line 10

def avg
  numerics?
  return Float::NAN if empty?

  map(&:to_f).sum / count
end

#compact(modifier = nil) ⇒ Object

Misc Operations #####



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/theusual/array.rb', line 49

def compact(modifier = nil)
  falsy = modifier == :falsy
  blanks = falsy || modifier == :blanks

  reject do |v|
    isblank = blanks && v.respond_to?(:empty?) && v.empty?
    isfalsy = falsy && (v == 0)

    !v || isblank || isfalsy
  end
end

#compact!(modifier = nil) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/theusual/array.rb', line 61

def compact!(modifier = nil)
  res = compact(modifier)
  clear

  # TODO: is there a better way than shift/reverse?
  res.each {|x| unshift x}
  reverse!
end

#grepv(regex) ⇒ Object

String Operations #####



34
35
36
# File 'lib/theusual/array.rb', line 34

def grepv regex
  reject { |elem| elem =~ regex }
end

#gsub(regex, replacement) ⇒ Object



39
40
41
# File 'lib/theusual/array.rb', line 39

def gsub(regex, replacement)
  map { |string| string.gsub(regex, replacement) }
end

#gsub!(regex, replacement) ⇒ Object



43
44
45
# File 'lib/theusual/array.rb', line 43

def gsub!(regex, replacement)
  map! { |string| string.gsub(regex, replacement) }
end

#stdObject Also known as: standard_deviation



20
21
22
23
24
25
26
27
28
29
# File 'lib/theusual/array.rb', line 20

def std
  numerics?
  return Float::NAN if empty?

  mean = avg

  Math.sqrt(
      map { |sample| (mean - sample.to_f) ** 2 }.reduce(:+) / count.to_f
  )
end

#sumObject Also known as: total

Numerical Operations #####



3
4
5
6
# File 'lib/theusual/array.rb', line 3

def sum
  numerics?
  inject 0, &:+
end