I have the following string from which I want to extract numerals into an array
b="yesterday: 136.00. current: *143.00*. change: *-7.00*. change_2: *5.15%*. high: 143.00. low: 143.00"
So I first did,
c = b.split(". ")
d = c.map{ |x| x.scan(/[\d\.-]+/)[0] }.map(&:to_f)
However d returns:
[136.0, 143.0, -7.0, 2.0, 143.0, 143.0]
Instead of
[136.0, 143.0, -7.0, 5.15, 143.0, 143.0]
Try just:
b.scan(/(?<=[ *])-?\d[\d.]+/).map(&:to_f)
# => [136.0, 143.0, -7.0, 5.15, 143.0, 143.0]
b.scan(/-?\d+.\d{2}[%*.]?/).map(&:to_f)
#=> [136.0, 143.0, -7.0, 5.15, 143.0, 143.0]
For something this complex I think you should use a regex, so something like this
/^yesterday: ([0-9+]) .. / =~ b
you can use rubular to help figure out the regex
Since it appears like you are trying to parse a fairly complex string and get a specific set of numbers from the "fields" in that string, a good way to do this is with a regex.
One of the best tools to determine exactly what that regex needs to be is Rubular.
If you are unfamiliar with parsing a string using regex , please see the Regex class in the docs http://www.ruby-doc.org/core-2.1.1/Regexp.html
For example the following regex would get each of those numbers into a corresponding variable. The reqex method is a little more complex but also shows what you are intending to do.
^yesterday: (?<yesterday>[-]*\d+\.\d+)\. current: \*(?<current>[-]*\d+\.\d+)\*\. change: \*(?<change>[-]*\d+\.\d+)\*\. change_2: \*(?<change_2>[-]*\d+\.\d+)%\*\. high: (?<high>[-]*\d+\.\d+)\. low: (?<low>[-]*\d+\.\d+)$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.