Mr. Baldan Mr. Baldan - 1 year ago 58
Ruby Question

Starting a simple data mining program. A method for writing values in variables from an entry text ruby

I want to write a simple program to collect data from pieces of texts by creating regular expressions to identify values through the phrases of the texts.

I want to start from something simple:

The car is red

I´m looking for a expression that let me to store the value red, or other possibles values such as blue, yellow, green if phrase changes. I want to do that from the interpreter or from a .txt file.

So my questions has two parts. One is to specify the value I want save. In this case "red", So I imagine a piece of code like {"The car is 'value'"} => value @color...Whatever be the regular expression that capture the syntax pattern of the language, Sorry I am not yet very familiar with the syntax of ruby , that's about precisely my question.
And the other part is about creating a variable to store the string "red" or whatever would be the case: yellow, green, brown...

I hope the question be clear.

Answer Source

It's pretty simple using a match group:

string = "The car is red. The car is blue"
regex = /The car is (\w+)/
matches = string.scan(regex)
print matches
# => [["red"], ["blue"]]
print matches.flatten(1)
# => ["red", "blue"]

(\w+) in the regex is the match group. The parenthesis are the start and end bounds of the match. The match is what will be returned by scan. You can use multiple match groups if you want.

\w in regex is a non-word-boundary character. \w+ effectively captures one word.

cucumber makes use of this approach