Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/sumhash/hash.rb
Constant Summary collapse
- NUMBER_CLASSES =
[Integer, Fixnum, Bignum, Float, Rational]
- SUPPORTED_CLASSES =
NUMBER_CLASSES + [Hash, OpenStruct]
Instance Method Summary collapse
-
#*(num) ⇒ Object
Multiplication.
-
#+(hash) ⇒ Object
Plus.
-
#+@ ⇒ Object
Unary plus.
-
#-(hash) ⇒ Object
Minus.
-
#-@ ⇒ Object
Unary minus.
-
#/(num) ⇒ Object
Division.
Instance Method Details
#*(num) ⇒ Object
Multiplication
44 45 46 47 48 49 50 |
# File 'lib/sumhash/hash.rb', line 44 def *(num) raise TypeError, "#{num.class} can't be coerced into Float" unless NUMBER_CLASSES.include? num.class self.inject({}) do |res, (k, v)| res[k] = SUPPORTED_CLASSES.include?(v.class) ? v*num : v res end end |
#+(hash) ⇒ Object
Plus
6 7 8 9 10 11 |
# File 'lib/sumhash/hash.rb', line 6 def +(hash) (self.keys + hash.keys).inject({}) do |sum, k| sum[k] = sum(self[k], hash[k]) sum end end |
#+@ ⇒ Object
Unary plus
30 31 32 |
# File 'lib/sumhash/hash.rb', line 30 def +@ self end |
#-(hash) ⇒ Object
Minus
14 15 16 17 18 19 |
# File 'lib/sumhash/hash.rb', line 14 def -(hash) (self.keys + hash.keys).inject({}) do |sum, k| sum[k] = sum(self[k], hash[k], :-) sum end end |
#-@ ⇒ Object
Unary minus
22 23 24 25 26 27 |
# File 'lib/sumhash/hash.rb', line 22 def -@ self.inject({}) do |res, (k, v)| res[k] = SUPPORTED_CLASSES.include?(v.class) ? -v : v res end end |
#/(num) ⇒ Object
Division
35 36 37 38 39 40 41 |
# File 'lib/sumhash/hash.rb', line 35 def /(num) raise TypeError, "#{num.class} can't be coerced into Float" unless NUMBER_CLASSES.include? num.class self.inject({}) do |res, (k, v)| res[k] = SUPPORTED_CLASSES.include?(v.class) ? v/num : v res end end |