Steve Tuckner <STUCKNER / MULTITECH.COM> writes:

> Maybe this is too dangerous but
> 
> File.readlines("test.txt").each {|line| print eval('"' + line + '"')}
> 
> will work. Even if there were a function such as String.interpolate(str) it
> would still be dangerous because any code within the #{} blocks would be
> evaluated!

indeed. 

im stuck with this version:

# ---
def interpolate(str) 
  reg = Regexp.new('#\{((\$|@|@@)\w+)\}')
  ret = ''
  while (match = reg.match(str))

    ret += match.pre_match
    for i in 1..(match.length-1)
      ret += yield(match[1])
    end
    
    str = match.post_match
    
  end
  ret += str
end

# testing calls:

a = '3012'
b = '1322'
str = 'foo "#{a} #{b}"'

p interpolate(str) {|match| eval(match)}
p interpolate('#{a}') {|match| eval(match)}

# ---

and i have 2 questions to the community:

1. i was not able to find an equivalent to perl's regexp-substitutes, so i had to do the
ugly/complex/inefficient loop-contruct in "interpolate". is there a better way to achieve
this in ruby?

2. i have to call interpolate with the eval block appended, so that the variables a
looked up in the scope of the calling environment. is there a more better way to do
this, or to make '{|match| eval(match)}' the default, if no block is supplied?


regards
messju


> Steve
> 
> -----Original Message-----
> From: Hal E. Fulton [mailto:hal9000 / hypermetrics.com]
> Sent: Friday, September 20, 2002 2:54 PM
> To: ruby-talk ML
> Subject: String interpolation at will?
> 
> 
> Maybe I'm overlooking something obvious,
> or maybe it's not possible.
> 
> We all know how convenient string interpolation
> can be: msg = "myval = #{myval}"
> 
> Is there a way to perform interpolation on
> an arbitrary string? For example, if the
> above string were read in from a file?
> 
> gsub doesn't count. :) Unless you have a
> particularly elegant way to use it.
> 
> Cheers,
> Hal