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.
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.
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.
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.
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.
Another way:
name = "my name is: andrew".split(/: */)[1] # => "andrew"
or
name = "my name is: andrew".split(/: */).last # => "andrew"
"my name is: andrew".split(/: */) # => ["my name is", "andrew"]
Then we select the second item:
["my name is", "andrew"][1] # => "andrew"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With