----- Original Message ----- 
From: "Hal E. Fulton" <hal9000 / hypermetrics.com>
To: "ruby-talk ML" <ruby-talk / ruby-lang.org>
Sent: Friday, September 20, 2002 4:06 PM
Subject: Re: String interpolation at will?


> ----- Original Message ----- 
> From: "Hal E. Fulton" <hal9000 / hypermetrics.com>
> To: "ruby-talk ML" <ruby-talk / ruby-lang.org>
> Sent: Friday, September 20, 2002 3:30 PM
> Subject: Re: String interpolation at will?
> 
> 
> > Hmm, there have been times I wished for a String.interpolate
> > method... couldn't be too hard to expose it. Wonder if it's
> > worth it?
> 
> To reply to myself: I've just remembered why
> this is nontrivial in pure Ruby. If you write 
> a String#interpolate, it can't get to your
> local variables, i.e. if you do:
> 
>   bar = "secret"
>   foo = 'code is #{bar}'
>   str = foo.interpolate
> 
> it won't work because #interpolate can't see
> the bar variable. Hmm.
> 
> You can still do it outside of a method, of 
> course.
> 
> I'm playing with a Proc now out of curiosity.

And to answer my own post again, I find that 
this works OK.

Tempted to put ANN: on the subject line.  ;)

Code below. 

Cheers,
Hal

  
  # Let's make a setter for a class variable
  class String
    def String.interp=(blk)
      @@interp = blk
    end
  end
  
  # Back to top-level scope
  String.interp = (Proc.new do |s|
    __str = s.dup
    __str.gsub!(/"/,'\"')
    eval('"' + __str + '"')
  end)
  
  # Now define the methods
  class String
    def String.interpolate(str)
      @@interp.call(str)
    end
    def interpolate
      @@interp.call(self)
    end
  end
  
  # Now try it out
  
  str = <<'END'
  He said, "I am the #{alpha} and
  the #{omega}."
  Have a nice day.
  
  END
  
  puts str
  
  alpha = "walrus"
  omega = "weather is fine"
  
  str2 = str.interpolate
  puts str2
  
  str3 = String.interpolate(str)
  puts str3
  
And the output is:

  He said, "I am the #{alpha} and
  the #{omega}."
  Have a nice day.

  He said, "I am the walrus and
  the weather is fine."
  Have a nice day.

  He said, "I am the walrus and
  the weather is fine."
  Have a nice day.