-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumex.rb
More file actions
74 lines (60 loc) · 1.51 KB
/
numex.rb
File metadata and controls
74 lines (60 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require 'active_support/concern'
require_relative 'math'
module Numex
extend ActiveSupport::Concern
module RightOperators
def right_operator_name(op)
:"__right_#{op}"
end
def right_operator(op, &body)
define_method(right_operator_name(op), &body)
end
end
class << self
include RightOperators
end
class_methods do
include RightOperators
end
right_operator :<=> do |a|
-(self <=> a)
end
right_operator :+ do |a|
self + a
end
right_operator :- do |a|
(-self).__send__(:'__right_+', a)
end
right_operator :* do |a|
self * a
end
right_operator :/ do |a|
(self**(-1)).__send__(:'__right_/', a)
end
module NumericExt
%i[<=> + - * / **].each do |op|
rop = Numex.right_operator_name(op)
define_method op do |b|
if b.respond_to? rop
b.__send__(rop, self)
else
super(b)
end
end
end
%i[< <= > >=].each do |op|
define_method op do |b|
if b.respond_to? :"__right_<=>"
b.__send__(:"__right_<=>", self).__send__(op, 0)
else
super(b)
end
end
end
end
end
# [Fixnum, Bignum, Rational, Complex, Float].each do |cls|
# cls.class_eval do
# prepend Numex::NumericExt
# end
# end