0

I have a hash like:

{:name => 'foo', :country => 'bar', :age => 22}

I also have a string like

Hello ##name##, you are from ##country## and your age is ##age##. I like ##country## 

Using above hash, I want to parse this string and substitute the tags with corresponding values. So after parsing, the string will look like:

Hello foo, you are from bar and your age is 22. I like bar

Do you recommend taking help of regex to parse it? In that case if I have 5 values in the hash, then I would have to traverse through string 5 times and each time parsing one tag. I don't think that is a good solution. Is there any better solution?

JVK
  • 3,782
  • 8
  • 43
  • 67

3 Answers3

3

Here is my solution to the problem:

h = {:name => 'foo', :country => 'bar', :age => 22}
s = "Hello ##name##, you are from ##country## and your age is ##age##. I like ##country##}"
s.gsub!(/##([a-zA-Z]*)##/) {|not_needed| h[$1.to_sym]}

It generally makes a single pass using regex and does the replacement I think you need.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Awesome. In fact I was also looking at ruby-doc's gsub 5 minutes before you replied. Thank you. I selected your answer. – JVK Dec 13 '12 at 09:22
0

It looks like there is a solution depending on what version of ruby you are using. For 1.9.2 you can use a hash, shown here: https://stackoverflow.com/a/8132638/1572626

The question is generally similar, though, so read the other comments as well: Ruby multiple string replacement

Community
  • 1
  • 1
wrhall
  • 1,288
  • 1
  • 12
  • 26
0

You can use String#gsub with a block:

    h = {:name => 'foo', :country => 'bar', :age => 22}
    s = 'Hello ##name##, you are from ##country## and your age is ##age##. I like ##country##'
    s.gsub(/##(.+?)##/) { |match| h[$1.to_sym] }