Here is one approach:
str.match(/"(.+)\s+(\d+)/)
puts "Name: #{$~[1]}"
puts "Price: #{$~[2]}"
#match (or any other regexp operator) populates the special variable $~, which is an array where element 0 contains the entire matched portion of the input, and elements 1..n contain the capture groups. This is often the best approach if you want to extract a number of fields from a single string.
Here is another approach:
puts "Name: #{str[/(.+)\s+(\d+)/, 1]}"
str[regexp, pos] is equivalent to "str.match(regexp) ; $~[pos]" and is nicely expressive when you only have one capture group that you’re interested in.
Return to home | Generated on 09/29/22