ruby eval('\1') of gsub possible?
I try to replace a sub-str by the content of a valiable where its name matches the sub-str by:
>> str = "Hello **name**"
=> "Hello **name**"
>> name = "John"
=> "John"
str.gsub(/\*\*(.*)\*\*/, eval('\1')) # => error!
the last line in the code above is a syntax error. and:
>> str.gsub(/\*\*(.*)\*\*/, '\1')
=> "Hello name"
>> str.gsub(/\*\*(.*)\*\*/, eval("name"))
=> "Hello John"
开发者_StackOverflow
what I want is the result of:
str.gsub(/\*\*(.*)\*\*/, eval("name")) # => "Hello John"
any help will be appreciated. thx!
Try this:
str = "Hello **name**"
name = "John"
str.gsub(/\*\*(.*)\*\*/) { eval($1) }
The gsub
method also accepts a block, which will be evaluated and the return value will be used as substitution. The special variables $1
, $2
, and so forth, are identical to using \1
in a string.
A slightly better alternative than using eval()
would be to use a Hash
with replacement values:
str = "Hello **name**"
names = { "name" => "John" }
str.gsub(/\*\*(.*)\*\*/) { names[$1] }
I realize this is not the answer to your question, but have you looked at Liquid markup? It essentially accomplishes the same thing by using double-braces {{}}
@template = Liquid::Template.parse("hi {{name}}") # Parses and compiles the template
@template.render( 'name' => 'tobi' ) # => "hi tobi"
精彩评论