Reputation: 712
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
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:
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
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
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