I am using Ruby version 1.8 because of legacy reason.
I have multiple hashes. I have a code logic that applies to the map
block on all my hashes.
hash1.map{|a| a['amount'].to_i * a['value'].to_i / 100}
I don't want to repeat that code logic every where like:
hash2.map{|a| a['amount'].to_i * a['value'].to_i / 100}
hash3.map{|a| a['amount'].to_i * a['value'].to_i / 100}
How can I pass a function call to the block so that the code logic would only be in a function which is easier for me to maintain?
I think the simplest thing would be to make a method that accepts that hash as an argument.
def map_totals(hash)
hash.map do |a|
a['amount'].to_i * a['value'].to_i / 100
end
end
totals1 = map_totals(hash1)
totals2 = map_totals(hash2)
totals3 = map_totals(hash3)
Or...
def calc_total(line_item)
line_item['amount'].to_i * line_item['value'].to_i / 100
end
totals1 = hash1.map { |li| calc_total(li) }
totals2 = hash2.map { |li| calc_total(li) }
totals3 = hash3.map { |li| calc_total(li) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With