Ben
Ben

Reputation: 712

How to extract digits from a String and transform them into an Integer

How to remove space between 2 numbers ? I have a String "1 026 personnes aiment ça" and I would like to get only 1026 (as Integer)

My attempt:

text = "1 026 personnes aiment ça"
# => "1 026 personnes aiment ça"
z = text.split(' ').first
# => "1 026"
z.to_i
# => 1
z.strip
# => "1 026"
z.class
# => String

Upvotes: 3

Views: 630

Answers (5)

Ashok Damaniya
Ashok Damaniya

Reputation: 303

"1 026 personnes aiment ça".gsub(' ', '').to_i
=> 1026

Upvotes: 1

Mendoza
Mendoza

Reputation: 124

I would use regular expressions (keep in mind this can get slow if you are doing a lot of iterations)

'1 026 personnes aiment ça'.match(/\d{1,3} \d{1,3}/)
                           .to_s
                           .tr(' ','')
                           .to_i
# => 3123

This would:

  • match the first 2 groups of 3 or fewer numbers
  • convert it to a string (MatchData only has method to convert the result to a string or an array)
  • replace spaces with an empty string
  • convert the string to an integer

    '1 026 personnes aiment ça'.match(/\d{1,3} \d{1,3}/)

Keeping in mind that this will silently fail, I would change the regex depending on what kind of text you are expecting.

For example; if you expect the first character of the string to be a digit, I would add ^ (indicates start of line).

'1 026 personnes aiment ça'.match(/^\d{1,3} \d{1,3}/)
                           .to_s
                           .tr(' ','')
                           .to_i

Upvotes: 0

Yaser Darzi
Yaser Darzi

Reputation: 1478

you can try this it`s work for me

(?<=\d) +(?=\d+(?:\s|$))

Upvotes: 1

Viktor
Viktor

Reputation: 2783

The #gsub method can replace all non-digit characters in the String and then you can transform it into an Integer with #to_i:

"1 026 personnes aiment ça".gsub(/\D/, "").to_i
#~> 1026

Upvotes: 3

Simon Crane
Simon Crane

Reputation: 2182

For your example, you can do:

text = "1 026 personnes aiment ça"
z = text.split(' ')
z = z[0]+ z[1]
z.to_i

Upvotes: 0

Related Questions