Class: MixedNumber

Inherits:
Numeric
  • Object
show all
Defined in:
lib/mixed_number.rb,
lib/mixed_number/version.rb

Defined Under Namespace

Classes: MixedNumberFormatError

Constant Summary collapse

DECIMAL_NUMBERS =
/^-?\d+(\.\d+)?$/
RATIONAL_NUMBERS =
/^-?\d+\/\d+$/
MIXED_NUMBERS =
/^-?\d+\s+\d+\/\d+$/
VALID_NUMBERS =
Regexp.union(DECIMAL_NUMBERS, RATIONAL_NUMBERS, MIXED_NUMBERS)
VERSION =
"1.0.3"

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



74
75
76
# File 'lib/mixed_number.rb', line 74

def method_missing(name, *args, &block)
	@rational.send(name, *args, &block)
end

Class Method Details

.parse(input = 0) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/mixed_number.rb', line 12

def parse(input=0)
	n = stringify(input).strip
	raise MixedNumberFormatError unless n =~ VALID_NUMBERS
	
	reduction_method = n =~ /^-/ ? :- : :+
	new(n.split.map { |r| Rational(r) }.reduce(reduction_method).to_r)
end

Instance Method Details

#+(other) ⇒ Object



42
43
44
45
46
# File 'lib/mixed_number.rb', line 42

def +(other)
	return to_s + other if other.is_a? String

	combine(:+, other)
end

#<=>(other) ⇒ Object



38
39
40
# File 'lib/mixed_number.rb', line 38

def <=>(other)
	@rational <=> other
end

#==(other) ⇒ Object



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

def ==(other)
	@rational == other
end

#coerce(other) ⇒ Object



54
55
56
# File 'lib/mixed_number.rb', line 54

def coerce(other)
	[MixedNumber(other), self]
end

#fractionObject



30
31
32
# File 'lib/mixed_number.rb', line 30

def fraction
	abs.to_r - whole.abs
end

#to_dObject



62
63
64
# File 'lib/mixed_number.rb', line 62

def to_d
	BigDecimal(@rational, 32)
end

#to_mObject Also known as: to_mixed



66
67
68
# File 'lib/mixed_number.rb', line 66

def to_m
	self
end

#to_sObject Also known as: to_str



58
59
60
# File 'lib/mixed_number.rb', line 58

def to_s
	@rational_string
end

#wholeObject



26
27
28
# File 'lib/mixed_number.rb', line 26

def whole
	to_i
end