iamtoc
iamtoc

Reputation: 1709

Ruby regex find and replace a number inside a string

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.

Upvotes: 2

Views: 5787

Answers (3)

steenslag
steenslag

Reputation: 80105

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

Upvotes: 2

ipd
ipd

Reputation: 5714

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.

Upvotes: 3

MrDanA
MrDanA

Reputation: 11647

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.

Upvotes: -2

Related Questions