2

How would I find and replace '49' when '49' will be an unknown id, using ruby on rails?

str = "select * from clients where client_id = 49 order by registration_date asc"
str = str.gsub(/someRegExThatFinds49/, replacement_id) # <------ Here's the concept

Looking for a syntax and example that's correct. Thanks.

4
  • 1
    Bigger question back, why are you editing an sql string in rails? You rarely ever need to touch sql in rails. what bigger problem are you trying to solve? Commented Mar 30, 2012 at 18:13
  • 1
    A word of warning - all the answers I'm seeing here are using gsub, which will replace all occurrences of the regex in the string. If you know your numeric ID will always be the first number in the string, regular sub will be safer, as it only replaces the first match. If your ID could be at any position, possibly with other numbers before it, regices probably aren't what you're looking for. It'd just be too easy to screw things up. Commented Mar 30, 2012 at 18:20
  • DGM, Each client is creating custom reports whereby 'str' is constructed dynamically by the client and stored as a string in the database. So the database table 'report' has hundreds of associated records in 'report_details' containing these sql queries. I'm fairly new to rails and needed to manipulate these records in some circumstances, and took this approach due to my limted knowledge of rails. Commented Mar 30, 2012 at 18:24
  • Xavier Holt, and very thankful you brought this up as I failed to mention this point you bring up in my original question/title, as I will for sure be encountering this scenario frequently. Commented Mar 30, 2012 at 18:28

3 Answers 3

3

This would work, using a copy of the string:

new_str = str.gsub(/\d+/, replacement_id)

Or, if you prefer to do it in place (modifying the string directly)

str.gsub!(/\d+/, replacement_id)

ian.

Sign up to request clarification or add additional context in comments.

Comments

2
unknown_id = 49
puts "hello4849gone".gsub(/#{unknown_id}/, "HERE") #=> hello48HEREgone

Comments

-2
str = str.gsub(/49/, replacement_id)

Or use the self-updating version:

str.gsub!(/49/, replacement_id)

Also, check out Rubular which allows you to test out regular expressions.

1 Comment

Sorry for the downvote, but the point of the question was to replace an arbitrary numeric ID.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.