避免"字符串不能被强制进入大十进制"



我编写了一个返回两个不同对象(整数和字符串(的逻辑/方法,例如返回的值将是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 代码一样足够智能?

所以这是我所做的:

重构逻辑。它按预期返回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.

关于解决此问题的最佳方法,我们可以考虑的另一件事是调查Interpolation以及我使用 Benchmark 确定其算法复杂性Join

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)

最新更新