Palandrel Palandrel - 1 year ago 89
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 ']'
... ^

How should I proceed?

Answer Source

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]

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)>]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download