Class: DataCalc

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ DataCalc

Returns a new instance of DataCalc.



6
7
8
9
10
# File 'lib/datacalc.rb', line 6

def initialize(input)
  @input = JSON.parse(input)
  @length = @input.length
  @output = nil
end

Instance Attribute Details

#inputObject

Returns the value of attribute input.



4
5
6
# File 'lib/datacalc.rb', line 4

def input
  @input
end

#lengthObject

Returns the value of attribute length.



4
5
6
# File 'lib/datacalc.rb', line 4

def length
  @length
end

#outputObject

Returns the value of attribute output.



4
5
6
# File 'lib/datacalc.rb', line 4

def output
  @output
end

Instance Method Details

#match(*matchnames) ⇒ Object

What: Gets list entries that include all values of arguments passed Input: Variable number of arrays with field name and value Output: Parsed JSON of entries that match all input arrays



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/datacalc.rb', line 26

def match(*matchnames)
  savefile = "[]"
  matchnames.each do |match|
    tmpfile = Array.new
    (0..@length-1).each do |l|
      if match[1] == (@input[l])[match[0]]
        tmpfile << @input[l]
        savefile = tmpfile.to_json
      end
    end
    @input = JSON.parse(savefile)
    @length = @input.length
  end
  @output = @input
end

#mean(col) ⇒ Object

What: Get average of a column Input: Column to get average of Output: Average



59
60
61
# File 'lib/datacalc.rb', line 59

def mean(col)
  mean = sum(col).to_f / @length.to_f
end

#sortalpha(sattr) ⇒ Object

What: Sorts in alphabetical order Input: Attribute to sort by Output: Sorted JSON



52
53
54
# File 'lib/datacalc.rb', line 52

def sortalpha(sattr)
  @input.sort_by {|e| e[sattr]}.to_json
end

#sortnum(sattr) ⇒ Object

What: Sorts in numerical order Input: Attribute to sort by Output: Sorted JSON



45
46
47
# File 'lib/datacalc.rb', line 45

def sortnum(sattr)
  @input.sort_by {|e| e[sattr].to_i}.to_json
end

#sum(col) ⇒ Object

What: Gets the sum of a column Input: Column to add up Output: Sum for column



15
16
17
18
19
20
21
# File 'lib/datacalc.rb', line 15

def sum(col)
  total = 0
  (0..@length-1).each do |l|
    total += (@input[l])[col].to_i
  end
  return total
end