Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call function in the map block of hash

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?

like image 215
Leem Avatar asked Jan 26 '23 13:01

Leem


1 Answers

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) }
like image 73
Alex Wayne Avatar answered Jan 30 '23 07:01

Alex Wayne