Module: Frakzio::InstanceMethods

Defined in:
lib/frakzio.rb

Instance Method Summary collapse

Instance Method Details

#decimal_to_array(d) ⇒ Object



75
76
77
78
79
80
# File 'lib/frakzio.rb', line 75

def decimal_to_array(d)
  precision   = 10**6
  numerator   = (d.to_f*precision).to_i

  simplify([numerator, precision])
end

#fraction_to_array(d) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/frakzio.rb', line 82

def fraction_to_array(d)
  result = []
  if d.include?(" ")
    result << d.split(" ").first.to_i
    result.concat get_fraction(d.split(" ").last)
  else
    result << nil
    result.concat get_fraction(d)
  end

  simplify(result)
end

#fraction_to_s(frac) ⇒ Object



99
100
101
102
103
104
105
# File 'lib/frakzio.rb', line 99

def fraction_to_s(frac)
  result = ""
  result += frac[0].to_s if frac[0] && frac[0] != 0
  result += " " if frac[0] && frac[0] != 0 && frac[1]
  result += "#{frac[1]}/#{frac[2]}" if frac[1] && frac[2]
  result
end

#fraction_valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
# File 'lib/frakzio.rb', line 30

def fraction_valid?(value)
  if value 
    value = value.to_s
    (value.match(/\A\d* *\d*\/?\d*\z/).to_s == value || value.match(/\A\d*\.?\d*\z/).to_s == value) ? true : false
  end
end

#frakzionize(s = "") ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/frakzio.rb', line 37

def frakzionize(s = "")
  s = "" unless s
  s = s.to_s
  if s.include?('.')
    frac = fraction_to_s(decimal_to_array(s))
  else if s.include?('/')
    frac = fraction_to_s(fraction_to_array(s))
    else
      s == "" ? s = nil : s = s
      frac = s
    end
  end
  frac
end

#get_fraction(s) ⇒ Object



95
96
97
# File 'lib/frakzio.rb', line 95

def get_fraction(s)
  s.split("/").map {|x| x.to_i}
end

#nwd(a, b) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/frakzio.rb', line 52

def nwd(a,b)
  while b!=0 do
    a,b = b,a%b
  end

  return a
end

#simplify(array) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/frakzio.rb', line 60

def simplify(array)
  index = array.size - 2
  entires = index == 0 ? 0 : array[index-1] ? array[index-1] : 0
    
  rest        = array[index]%array[index+1]
  entires     += array[index]/array[index+1]
  n           = nwd(rest, array[index+1])
  numerator   = rest/n
  denominator = array[index+1]/n

  numerator = denominator = nil if numerator == 0

  [entires, numerator, denominator]
end