Zach Smith
Zach Smith

Reputation: 8971

selecting from the beginning to a substring of a string in ruby

if i have a string = "helloiamastring"

and i want to select from the beginning of the string to the "lo". how can i do that?

i thought it would be something along the lines of

string[/\A/.."lo"]

or string[/\A/../lo/]

that would give me "hello". alas it doesn't and i don't know where to look

(i also need to be able to do this without knowing where in the string the "lo" is positioned)

I'm new. I'm sure I've read how to do this somewhere but i can't remember where. any help would be appreciated!

thanks,

Upvotes: 0

Views: 77

Answers (2)

Johnny Graber
Johnny Graber

Reputation: 1467

This should do the job:

string = "helloiamastring"
string[/\A.*[lo]/]
=> "hello"

Or if you want it to stop at the first lo you can do this:

 string[/\A.*?lo/]

Upvotes: 1

Stefan
Stefan

Reputation: 114248

This would work:

"helloiamastring"[/.*lo/]
#=> "hello"

If there are multiple occurrences of lo and you want to match only the first one, use /.*?lo/ instead.

Upvotes: 5

Related Questions