ruby -特定键的转换值[1]

sqougxex  于 2023-01-30  发布在  Ruby
关注(0)|答案(1)|浏览(108)

我尝试对每一行比较每个对应名称的fx值;因此,结果应该是:diff={"name"=>"XPT", "fx"=>"1.1315313597682419"}或四舍五入,然后再进行比较_如果这样更容易的话:diff={"name"=>"XPT", "fx"=>"1.13153"}
到目前为止,我有一个TypeError(没有将String隐式转换为Integer),如下所示:

def compare_values
    diff = {}
    a = [{"src"=>"reportStack"},
    {"name"=>"XPT", "fx"=>"1.1315313597682419"},
    {"name"=>"XAU", "fx"=>"27.0165670831070071"},
    {"name"=>"XAG", "fx"=>"8.4192241535397429"}]

    b = [{"src"=>"reportOverflow"},
    {"name"=>"XPT", "fx"=>"1.13163"},
    {"name"=>"XAU", "fx"=>"27.0165670831070071"},
    {"name"=>"XAG", "fx"=>"8.4192"}]

    b.each do |b_row|
       a.each do |a_row|
          b.each do |k,v|
            diff = k if a_row['name'].value == e_row['name'].value && a_row['fx'].value.to_f != a_row['fx'].value.to_f
          end
      end
    end
end

有谁能给予我一个如何处理这种泡菜的建议吗?

f2uvfpb9

f2uvfpb91#

开始,我将reportStack(a)和reportOverflow(b)的数据结构简化为散列,其中键为name,值为fx,这将允许我们比较键-值对,而不必迭代数组并检查每个值。

report_stack = a.inject(Hash.new) do |memo, report_stack_entry|
  next memo unless report_stack_entry['name']

  memo[report_stack_entry['name']] = report_stack_entry['fx']
  memo
end

# report_stack => {"XPT"=>"1.1315313597682419", "XAU"=>"27.0165670831070071", "XAG"=>"8.4192241535397429"}

report_overflow = b.inject(Hash.new) do |memo, report_overflow_entry|
  next memo unless report_overflow_entry['name']

  memo[report_overflow_entry['name']] = report_overflow_entry['fx']
  memo
end

# report_overflow => {"XPT"=>"1.13163", "XAU"=>"27.0165670831070071", "XAG"=>"8.4192"}

然后,我将在report_stack上使用.reject,并在相应的report_overflow键上使用!nil?start_with?==条件

diff = report_stack.reject do |name, fx|
  overflow_fx = report_overflow[name]

  !overflow_fx.nil? && (
    fx == overflow_fx ||
    fx.start_with?(overflow_fx)
  )
end

diff #=> {"XPT"=>"1.1315313597682419"}

如果需要任何额外的比较逻辑,您应该能够轻松地更新.reject块中的条件。

相关问题