gpt4 book ai didi

ruby-on-rails - HashMap block 中的调用函数

转载 作者:行者123 更新时间:2023-12-04 06:09:08 25 4
gpt4 key购买 nike

由于遗留原因,我正在使用 Ruby 1.8 版。

我有多个哈希值。我有一个适用于 map 的代码逻辑阻止我所有的哈希。

hash1.map{|a| a['amount'].to_i * a['value'].to_i / 100}

我不想在每个地方重复该代码逻辑,例如:
hash2.map{|a| a['amount'].to_i * a['value'].to_i / 100}
hash3.map{|a| a['amount'].to_i * a['value'].to_i / 100}

如何将函数调用传递给块,以便代码逻辑只在我更容易维护的函数中?

最佳答案

我认为最简单的方法是创建一个接受该散列作为参数的方法。

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)

或者...
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) }

关于ruby-on-rails - HashMap block 中的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59145837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com