Module: HashHelper::Percentage
Instance Method Summary collapse
-
#deep_transform_values_to_percentages(relative: true, precision: nil) ⇒ Hash
Transforms all numeric values in the hash into percentages.
Methods included from DeepSum
Instance Method Details
#deep_transform_values_to_percentages(relative: true, precision: nil) ⇒ Hash
Transforms all numeric values in the hash into percentages.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/hash_helper/percentage.rb', line 22 def deep_transform_values_to_percentages(relative: true, precision: nil) total_sum = deep_sum calculate_percentage = lambda do |value| return value unless value.is_a?(Numeric) return value unless total_sum.positive? percentage = (value / total_sum.to_f * 100) precision ? percentage.round(precision) : percentage end unless relative return deep_transform_values { |value| calculate_percentage.call(value) } end transform_values do |value| case value when Hash value.deep_transform_values_to_percentages(relative: relative, precision: precision) else calculate_percentage.call(value) end end end |