Question

I have 2 questions

I have a rails app that fetches market data about currencies from an rss feed that returns data in the following format

a = ["31.25", "*33.00*", "*+1.75*", "*5.60%*", "33", "33"]
b = ["3.55", "*3.45*", "*-0.10*", "*-2.82%*", "3.5", "3.4"]

I need to store this values in a database as decimal data type columns for precision purposes since I'm dealing with money.

The first question is:

I need to convert the above arrays to the following format,

 a = [31.25,33.00,1.75,5.60,33,33]

 b = [3.55,3.45,-0.10,2.82,3.5,3.4]

And the second question is,

What rails command should I use to create a model for sqlite and postgresql databases with one-column that has capabilities to store signed decimals e.g. +1.75 and -0.10

I've tried

rails g model currency dollar:decimal

Instead, when I save -0.10 in this model and then query for it using,

Currency.last.dollar

the following is returned,while I just need it to return -0.10

#<BigDecimal:ae244d8,'0.0',9(27)> 
Was it helpful?

Solution

First question:

a.map{ |x| x.scan(/[\d\.-]+/)[0] }.map(&:to_f)

Second:

Currency.first.dollar.to_f # => -0.1

Or this maybe more proper:

add_column :currency, :dollar, :decimal, precision: 8, scale: 2

OTHER TIPS

Use regexps:

f = []
a.each do |i|
  f << i.match(/\-?[0-9]{1,2}(\.[0-9]{1,2})?/)[0].to_f
end

puts f

If you have a lot of data then use precompired regexp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top