Skip to content

Instantly share code, notes, and snippets.

@leejarvis
Created October 4, 2012 09:27
Show Gist options
  • Save leejarvis/3832504 to your computer and use it in GitHub Desktop.
Save leejarvis/3832504 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
def get_values(string, expression)
regex = Regexp.new(expression.gsub(/\{([^\}]+)\}/) { "(?<#{$1}>\\S+)" })
(match = regex.match(string)) ? Hash[match.names.zip(match.captures)] : {}
end
p get_values "Alice is 23 years old", "{name} is {age} years old" #=> {"name"=>"Alice", "age"=>"23"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment