Reputation: 2289
This is my line of code:
col_value = line_item[column].scan(/\d+./).join().to_i
When I enter 30,000 into the textfield, col_value is 30. I want it to bring in any number: 30,000 30.5 30.55 30000
Any of these are valid...
Is there a problem with the scan and or join which would cause it to return 30? Using the suggested regexes below still retunrs 30 e.g.
col_value = line_item[column].scan(/\d+[,.]?\d+/).join().to_i
Could it be that "to_i
" converts "30,000" to 30??
Upvotes: 1
Views: 626
Reputation: 110675
Yes, "30,000".to_i #=> 30"
. See String#to_i: "Extraneous characters past the end of a valid number are ignored."
I suggest you first remove the commas, then apply a regex:
R = /
\d+ # match >= 0 digits
| # or
\d+\.\d+ # match > 0 digits, a decimal point, then > 0 digits
/x # extended mode
str = "30,000 30.5 30.55 30000 1. .1"
str1 = str.tr(',','')
#=> "30000 30.5 30.55 30000 1. .1"
a = str1.scan(R)
#=> ["30000", "30", "5", "30", "55", "30000"]
a.map(&:to_i)
#=> [30000, 30, 5, 30, 55, 30000]
After chaining, we have:
str.tr(',','').scan(R).map(&:to_i)
If the desired solution is instead:
#=> [30000, 30, 5, 30, 55, 30000, 1, 0]
the regex needs to be modified as follows:
R = /
\d+ # match >= 0 digits
| # or
\d+\.\d+ # match > 0 digits, a decimal point, then > 0 digits
| # or
\d+\. # match > 0 digits, then a decimal point
| # or
\.\d+ # match a decimal point, then > 0 digits
/x # extended mode
Upvotes: 0