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

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

See

  1. split
  2. strip

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" 

Tags:

Ruby