numeric_hash 0.3.0 → 0.3.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,3 +1,3 @@
1
1
  class NumericHash < Hash
2
- VERSION = "0.3.0"
2
+ VERSION = "0.3.1"
3
3
  end
data/lib/numeric_hash.rb CHANGED
@@ -180,8 +180,24 @@ class NumericHash < Hash
180
180
  # @hash.collect_numeric(&:to_s) # => { :a => "1", :b => { :c => "2", :d => "3" } }
181
181
  #
182
182
  def collect_numeric(&block)
183
+ # First attempt to map into a NumericHash.
184
+ map_to_hash(NumericHash) do |key, value|
185
+ if value.is_a?(NumericHash)
186
+ result = value.collect_numeric(&block)
187
+ else
188
+ result = yield(value)
189
+
190
+ # If the mapped value not Numeric, abort so that we try again by
191
+ # mapping into a regular Hash.
192
+ raise TypeError.new('result is not Numeric') unless result.is_a?(Numeric)
193
+ end
194
+ [key, result]
195
+ end
196
+ rescue TypeError
197
+ # At least one of the values mapped into a non-Numeric result; map into a
198
+ # regular Hash instead.
183
199
  map_to_hash do |key, value|
184
- [key, value.is_a?(NumericHash) ? value.collect_numeric(&block) : yield(value)]
200
+ [key, value.is_a?(NumericHash) ? value.collect_numeric(&block) : yield(value) ]
185
201
  end
186
202
  end
187
203
  alias_method :map_numeric, :collect_numeric
@@ -224,7 +240,7 @@ protected
224
240
  elsif value.respond_to?(:to_int)
225
241
  value.to_int
226
242
  else
227
- raise ArgumentError.new("cannot convert to Numeric: #{value.inspect}")
243
+ raise TypeError.new("cannot convert to Numeric: #{value.inspect}")
228
244
  end
229
245
  end
230
246
 
@@ -239,9 +255,9 @@ protected
239
255
  # First value is (or can be converted into) a Numeric
240
256
  value1 = convert_to_numeric(value1)
241
257
  if value2.is_a?(NumericHash)
242
- # Second value is a NumericHash; each of its hash values should be
258
+ # Second value is a NumericHash; each of its Numeric values should be
243
259
  # applied to the first value.
244
- value2.map_values { |value2_sub_value| value1.__send__(operator, value2_sub_value) }
260
+ value2.map_numeric { |value2_sub_value| value1.__send__(operator, value2_sub_value) }
245
261
  else
246
262
  # Second value also is (or can be converted into) a Numeric; apply the
247
263
  # two values directly.
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: numeric_hash
3
3
  version: !ruby/object:Gem::Version
4
- hash: 19
4
+ hash: 17
5
5
  prerelease:
6
6
  segments:
7
7
  - 0
8
8
  - 3
9
- - 0
10
- version: 0.3.0
9
+ - 1
10
+ version: 0.3.1
11
11
  platform: ruby
12
12
  authors:
13
13
  - Clyde Law