views:

80

answers:

3

I have the following string:

"h3. My Title Goes Here" 

I basically want to remove the first 4 characters from the string so that I just get back:

"My Title Goes Here".  

The thing is I am iterating over an array of strings and not all have the h3. part in front so I can't just ditch the first 4 characters blindly.

I have checked the docs and the closest thing I could find was chomp, but that only works for the end of a string.

Right now I am doing this:

"h3. My Title Goes Here".reverse.chomp(" .3h").reverse

This gives me my desired output, but there has to be a better way right? I mean I don't want to reverse a string twice for no reason.

I am new to programming so I might have missed something obvious, but I didn't see the opposite of chomp anywhere in the docs. Is there another method that will work?

Thanks!

+2  A: 

A standard approach would be to use regular expressions:

"h3. My Title Goes Here".gsub /^h3\. /, '' #=> "My Title Goes Here"

gsub means globally substitute and it replaces a pattern by a string, in this case an empty string.

The regular expression is enclosed in / and constitutes of:

^ means beginning of the string
h3 is matched literally, so it means h3
\. - a dot normally means any character so we escape it with a backslash
is matched literally

Jakub Hampl
Cool. Thanks for the great explanation.
James
+3  A: 

You can use sub with a regular expression:

s = 'h3. foo'
s.sub!(/^h[0-9]+\. /, '')
puts s

Output:

foo

The regular expression should be understood as follows:

^     Match from the start of the string.
h     A literal "h".
[0-9] A digit from 0-9.
+     One or more of the previous (i.e. one or more digits)
\.    A literal period.
      A space (yes, spaces are significant by default in regular expressions!)

You can modify the regular expression to suit your needs. See a regular expression tutorial or syntax guide, for example here.

Mark Byers
Cool. Thanks a bunch!
James
+3  A: 

To alter the original string, use sub!, e.g.:

my_strings = [ "h3. My Title Goes Here", "No h3. at the start of this line" ]
my_strings.each { |s| s.sub!(/^h3\. /, '') }

To not alter the original and only return the result, remove the exclamation point, i.e. use sub. In the general case you may have regular expressions that you can and want to match more than one instance of, in that case use gsub! and gsub—without the g only the first match is replaced (as you want here, and in any case the ^ can only match once to the start of the string).

Arkku
Good point about the sub vs gsub. If I understand correctly sub will definitely be better in this case since there is no point checking the whole string. I only need the first occurrence at the very beginning of the string. Thanks!
James
+1 Good point - I forgot that Ruby has both `sub` and `gsub` and have fixed my answer.
Mark Byers