Ruby remove everything after first space
-
07-06-2021 - |
Question
<%= @contact.foo_help %>
Outputs a number id and title (with a space between them), ex: 29292 This Is A Title. I just want the number. It won't always be the same amount of digits, and ocassionly I use numbers in my titles.
I was thinking the easiest way would be to gsub everything after the first space out, but I'm two weaks into this framework and can't get the synstax right! Please help
<%= @contact.foo_help.gsub( \s ' ') %>
Solution
@contact.foo_help.gsub(/\s.+/, '')
Will match a space followed by one or more of any characters, and replace with an empty string.
Rubular is wonderful for this sort of thing http://rubular.com/
OTHER TIPS
Try this
str = "29292 This Is A Title"
number = str.to_i
=> 29292
number.class
=> Fixnum
'29292 555 This Is A Title 8989'.to_i
=> 29292
Hope this will help you.
I think the easiest/cleanest thing would be to use String#[]
with a regex argument:
<%= @contact.foo_help[/\d+/] %>
For example:
>> '29292 This Is A Title.'[/\d+/]
=> "29292"
>> '29292 This 9999 Is A Title.'[/\d+/]
=> "29292"
You could also tighten it up a bit and anchor the regex at the beginning of the string:
<%= @contact.foo_help[/\A\d+/] %>
but I don't know if you need the extra noise.
The basic idea is to say what you mean ("give me the number at the beginning of the string and I know it will begin with a number") rather than grabbing what you don't want and throwing it away.