Home > Enterprise >  how to get numbers from array of strings?
how to get numbers from array of strings?

Time:08-16

I have this array of strings.

["Anyvalue", "Total", "value:", "9,999.00", "Token", " ", "|", " ", "Total", "chain", "value:", "4,948"]

and I'm trying to get numbers in one line of code. I tried many methods but wasn't really helpful as am expecting.

I'm using one with grep method:

array.grep(/\d /, &:to_i)  #[9, 4]

but it returns an array of first integers only. It seems like I have to add something to the pattern but I don't know what.

Or there is another way to grab these numbers in an Array?

CodePudding user response:

you can use:

array.grep(/[\d,] \.?\d /)

if you want int:

array.grep(/[\d,] \.?\d /).map {_1.gsub(/[^0-9\.]/, '').to_i}

and a faster way (about 5X to 10X):

array.grep(/[\d,] \.?\d /).map { _1.delete("^0-9.").to_i }
  • Related