Sakshi Malhotra
Sakshi Malhotra

Reputation: 95

String Replacement Ruby regex

I need to replace a string of characters with a sequence; I am using the gsub method

Say,

name = "Tom"

and this appears in a text as $(name) i need to replace $(name) with Tom.

Now, it is replacing only name with Tom and not $(name) with Tom. Can you tell me how the gsub will be like.

Upvotes: 1

Views: 430

Answers (3)

steenslag
steenslag

Reputation: 80105

str = "and this appears in a text as $(name) i need to replace $(name) with Tom."
str.tr!("$()","%{}") # use ruby's sprintf syntax %{name}
some_name = "Tom"

p str % {name: some_name}
# => "and this appears in a text as Tom i need to replace Tom with Tom."

Upvotes: 2

tadman
tadman

Reputation: 211740

Don't forget to properly escape things:

string = "My name is $(name)"

string.gsub(/\$\(name\)/, "Tom")
# => My name is Tom

Of course you can easily make this more generic:

substs = {
  name: "Tom"
}

string.gsub(/\$\((\w+)\)/) do |s|
  substs[$1.to_sym]
end

Upvotes: 3

undur_gongor
undur_gongor

Reputation: 15954

str.gsub('$(name)', 'Tom')

or, with a regexp

str.gsub(/\$\(name\)/, 'Tom')

Upvotes: 2

Related Questions