避免“String can't be coerced into BigDecimal”

Avoiding `String can't be coerced into BigDecimal`

我写了一个 logic/method returns 两个不同的对象(整数和字符串),例如返回的值将是 5000.00 Dollars

所以我写了一个方法来满足我的期望。看下面的逻辑:

s = x.currency # This assigns the string `dollarpounds` to s
a = s.slice(6..11) # This slice off 6 to 11 and returns just pounds to variable a
price_value = x.price # This is integer (price)
volume_volume = x.volume # This is integer (volume)
value = price_value * volume_volume # This multiplies price and volume and returns the value
value + "#{a}" # Now this throws TypeError-String can't be coerced into BigDecimal

所以为了解决这个问题,我重构了我的方法,但我认为它非常侮辱性的片段被认为是 Ruby 中的大师。 我如何重写下面这个重构的逻辑,使其足够智能作为 Ruby 代码?

所以这是我所做的:

重构逻辑。它 returns 5000.00 Dollars 符合预期

s = x.currency # This assigns the string `dollarpounds` to s
a = s.slice(6..11) # This slice off 6 to 11 and returns just pounds to variable a
price_value = x.price # This is integer (price)
volume_volume = x.volume # This is integer (volume)
value = price_value * volume_volume # This multiplies price and volume and returns the value
[[value].join(' '), "#{a}"].split(',').join(' ') # This returns 5000.00 Dollars

尽管我的 re-factored 代码有效,但我仍然觉得它对 ruby 社区是一种侮辱,并且可以做得更好。任何帮助如何做得更好将不胜感激。

使用插值:

"#{value} #{a}"

或串联:

value.to_s + ' ' + a

很有趣我如何在重构的最后一行使用插值 [[value].join(' '), "#{a}"].split(',').join(' ') 而且我从来没有将它调暗以简单地使用插值。除了答案线程中建议的插值之外,我还能够使代码更简单、更小、更快。

s = x.currency
a = s.slice(6..11)
value = x.price * x.volume
"#{value} #{a}" # Thanks to @PavelPuzin for this suggestion in this line.

关于解决此问题的最佳方法,我们可以考虑的另一件事是调查 InterpolationJoin 我使用基准测试来确定其算法复杂性:

require "benchmark"

numbers = (1..1000).to_a

n = 1000
Benchmark.bm do |x|
  x.report { n.times do   ; numbers.each_cons(2) {|a, b| "#{a} #{b}"}; end }
  x.report { n.times do   ; numbers.each_cons(2) {|a, b| [a, b].join(" ")}; end }
end 

###############################Result###################################
    user     system      total        real
   0.467287   0.000731   0.468018 (  0.468641)
   1.154991   0.001563   1.156554 (  1.157740)