Palandrel Palandrel - 3 months ago 10
Ruby Question

Array of BigDecimals from a CSV file

In my Rails app I need to create an array of BigDecimal from a CSV file. This code

eval("[#<BigDecimal:7fabfeadef60,'0.6E1',9(18)>, #<BigDecimal:7fabfeadef10,'0.22995E5',9(18)>]")


produce the following error message

SyntaxError: (eval):1: syntax error, unexpected end-of-input, expecting ']'
...fabfeadef10,'0.22995E5',9(18)>]
... ^


How should I proceed?

Answer

This string is not the best way to store an array. Retrieving the information is a bit clumsy, as demonstrated below. Have a look at Marshal for dumping and restoring objects.

require "bigdecimal"

str = "[#<BigDecimal:7fabfeadef60,'0.6E1',9(18)>, #<BigDecimal:7fabfeadef10,'0.22995E5',9(18)>]"

ar = str.split(">, #").map do |el|
  value  = el.split(",")[1][2..-2]
  BigDecimal.new(value)
end

p ar # => [#<BigDecimal:2161280,'0.6E1',9(18)>, # =><BigDecimal:21610c8,'0.22995E5',9(18)>]

# Much easier: Marshal

dumped = Marshal.dump(ar)
p retrieved = Marshal.load(dumped) # => [#<BigDecimal:f3cfa0,'0.6E1',9(18)>, #<BigDecimal:f3cf00,'0.22995E5',9(18)>]