Afolabi Olaoluwa
Afolabi Olaoluwa

Reputation: 1948

Avoiding `String can't be coerced into BigDecimal`

I wrote a logic/method that returns a two different objects (Integer and String), such that for an example the returned value will be 5000.00 Dollars.

So I wrote a method to for my expectations. See the logic below:

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

So to do away with this problem I refactored my method but I think its very insulting snippet to be considered a master in Ruby. How do I re-write this re-factored logic below to be smart enough as Ruby code?

So here is what I have done:

Re-factored logic. It returns 5000.00 Dollars as expected

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

As much my re-factored code works, I still feel it's insulting to ruby community and can be better than this. Any help how to do it better will be appreciated.

Upvotes: 0

Views: 566

Answers (2)

Afolabi Olaoluwa
Afolabi Olaoluwa

Reputation: 1948

Quite funny how I used interpolation in the last line of the refactor [[value].join(' '), "#{a}"].split(',').join(' ') and I never dim it fit to simply use Interpolation. Aside the suggested interpolation by in the answers thread, I was able to make the code more simple, smaller, and faster.

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

Another thing we can consider about the best way to go about this is to investigate Interpolation and the Join I used by using Benchmark to determine its Algorithmic Complexity:

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)

Upvotes: 0

Pavel Puzin
Pavel Puzin

Reputation: 36

Use interpolation:

"#{value} #{a}"

Or concatenation:

value.to_s + ' ' + a

Upvotes: 2

Related Questions