1

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.

3
  • Show your gsub, perhaps? Also, why do you replace name and not $(name)? Commented Jul 7, 2015 at 19:00
  • The my_hash contains the name =>Tom correspondence. The gsub is as line.gsub($2 , my_hash). I get $2 from the regex that gives me "name" Commented Jul 7, 2015 at 19:02
  • @SergioTulentsev: I need to replace $(name). now the output I am getting is $(Tom), not only Tom Commented Jul 7, 2015 at 19:06

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Can you show me an implementation of your second code. I am very new to ruby and would like to know how to use it
You mean an explanation? That's a regular expression that captures word-like values (\w+) and uses that to look-up in a Hash what to replace it with. That can be a lot to take in at first, but take it bit by bit and you'll come to understand it better. Techniques like this can do a lot of work with very little code. If you've got a good Ruby reference, that helps considerably.
2
str.gsub('$(name)', 'Tom')

or, with a regexp

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

Comments

2
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."

2 Comments

That is a clever approach, though hopefully no %{...} content was present in the original.
thanks, but i don't think i will be able to use this as i am not aware in the data i will be parsing if i may encounter a %{...}

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.