Andrew
Andrew

Reputation: 238717

Ruby: How to parse a string to pull something out and assign it to a variable

I have a string that looks something like this:

"my name is: andrew"

I'd like to parse the string, pull out the name from the string, and assign it to a variable. How would I do this with Ruby?

Update:

The string I used as an example was only an example. The strings that I will be working with can change formats, so you can't rely on the colon being in the actual example. Here are a few examples that I'm working with:

"/nick andrew"     # command: nick, value: "andrew"
"/join developers" # command: join, value: "developers"
"/leave"           # command: leave, value: nil

I'd like to use some sort of regular expression to solve this (since the string can change formats), rather than splitting the string on certain characters or relying on a certain character position number.

Upvotes: 10

Views: 43318

Answers (5)

Sean Vikoren
Sean Vikoren

Reputation: 1094

Another way:

name = "my name is: andrew".split(/: */)[1] # => "andrew"

or

name = "my name is: andrew".split(/: */).last # => "andrew"

Breaking it down, first we break it into parts. The regular expression /: */ says a : followed by any number of spaces will be our splitter.
"my name is: andrew".split(/: */) # => ["my name is", "andrew"]

Then we select the second item:

["my name is", "andrew"][1] # => "andrew" 

Upvotes: 9

Andrew
Andrew

Reputation: 238717

This tutorial really helped me understand how to work with regular expressions in Ruby.

One way to use a regular expression to get the string you want is to replace the stuff you don't want with an empty string.

original_string = "my name is: andrew"
name = original_string.sub(/^my name is: /, '') # => 'andrew'

another_format = "/nick andrew"
name = another_format.sub(/^\/nick /, '') # => 'andrew'

However, that's just string replacement/substitution. The regex is not capturing anyting.

To capture a string using a regular expression, you can use the Ruby match method:

original_string = "my name is: andrew"
matches = original_string.match /^my name is: (.*)/
name = matches[1] # return the first match

Upvotes: 7

DigitalRoss
DigitalRoss

Reputation: 146073

s.split.last

That should work with all of your cases.

Upvotes: 2

Zabba
Zabba

Reputation: 65467

One way to do that is:

s = "my name is: andrew"
pos = (s =~ /(?!.*:).*/)
result = s[pos..-1]
p result.strip!  # "andrew"

Another:

s = "my name is: andrew";
p s.slice(s.index(":")..-1) # "andrew"

Upvotes: 3

Sahil Muthoo
Sahil Muthoo

Reputation: 12496

s = "my name is: andrew"
p s.split(':')[1].strip # "andrew"

See

  1. split
  2. strip

Upvotes: 15

Related Questions