Jorge Cuevas Jorge Cuevas - 4 months ago 5x
Ruby Question

How to find and save a string section in ruby on rails 4?

I need to find a section of a string that includes the substring

"print time:"
and save it with the time it displays after the colon on the database.

What I've used until now is the
helper and the
helper to start the search but I'm not sure how to actually execute a search inside the string.

How can I find the section of the string so that I can save it afterwards?


Use regular expressions, which in Ruby can be written with the /…/ syntax and matched against using String#match.

log = "username: jsmith\nprint time: 08:02:41\npower level: 9001"
print_time = log.match(/print time:\s*([^\n]+)\s*\n/)[1]
p print_time # => "08:02:41"

The regex /print time:\s*([^\n]+?)\s*\n/ matches any text after “print time:”, on the same line, ignoring surrounding whitespace \s*, and saves it as the first capture group using the (). Then [1] selects the contents of that first capture group.

After extracting the print_time string, you can do whatever you need to with it. For example, if you had a Rails model PrintTime, you might save the extracted time to the database with PrintTime.create(extracted_time: print_time).