1
<%= @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 ' ')  %>
jahrichie
  • 1,215
  • 3
  • 17
  • 26
  • Are you using Rails, or just Ruby? – Andrew Grimm May 11 '12 at 05:23
  • `gsub'`s arguments need to be separated by commas and the first argument has to be a string or a regular expression. If you want the latter, you have to use a regex literal (`/\s/`). I know you are new to the language, but that's basic stuff from ever howto or the documentation. – Michael Kohl May 11 '12 at 07:29

3 Answers3

7
@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/

DVG
  • 17,392
  • 7
  • 61
  • 88
5

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
5

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.

suvankar
  • 1,548
  • 1
  • 20
  • 28