Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 419
Andrew Avatar asked Nov 04 '11 17:11

Andrew


People also ask

How do you add a string to a variable in Ruby?

Instead of terminating the string and using the + operator, you enclose the variable with the #{} syntax. This syntax tells Ruby to evaluate the expression and inject it into the string.

How do you split a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

How do you split a string into an array of words in Ruby?

The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.

How do I parse a string?

String parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class. String parsing can also be done through StringTokenizer.


1 Answers

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" 
like image 163
Sean Vikoren Avatar answered Nov 03 '22 11:11

Sean Vikoren