I am receiving a JSON post into my Rails 3 application. I am then parsing each of the values and inserting them into the application database. It’s all working well but now I would like to modify the received values before inserting them into the database.
:subject => email_payload['subject']
As the above code shows, I am inserting the received value for ‘subject’ into the column named ‘subject’.
In the example above the received value is like this:
Results from Example Company - Surname/Firstname/[12345]
What I would like to do is strip everything out except the numerical value between the []. So the value that’s inserted into the database is simply:
12345
I can, presumably, just select anything from 0-9 but how do I add regex to the received string?
None of the following seem to work:
['subject.gsub!([0-9])']
['subject'.gsub!([0-9])]
['subject'].gsub!([0-9])
I’ve tested the Regex here http://rubular.com/r/AVFkm3A440
Since you are applying the
.gsub()to the value returned by the hash keyemail_payload['subject'], the method belongs chained outside the closing].Your regular expression is missing its
/delimiters. To capture the group as a whole, add a+as in/[^0-9]+/. The^will match all non-digit characters, and then.gsub()will replace them with an empty string. So the pattern below will mutate the keyemail_payload['subject']in place