JVK
JVK

Reputation: 3912

An efficient way of custom tag parsing in ruby

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?

Upvotes: 0

Views: 106

Answers (3)

Aaron Tinio
Aaron Tinio

Reputation: 81

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] }

Upvotes: 0

Boris Strandjev
Boris Strandjev

Reputation: 46943

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.

Upvotes: 3

wrhall
wrhall

Reputation: 1308

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

Upvotes: 0

Related Questions