From: M Mohr Date: 2002-09-23T21:16:09+09:00 Subject: Re: String[#.]interpolate (was Re: String interpolation at will?) "Hal E. Fulton" writes: > ----- Original Message ----- > From: "Hal E. Fulton" > To: "ruby-talk ML" > Sent: Friday, September 20, 2002 4:06 PM > Subject: Re: String interpolation at will? > > > > ----- Original Message ----- > > From: "Hal E. Fulton" > > To: "ruby-talk ML" > > 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. very nice. but, unless i am missing something, there is just one flaw: String.interp is always called in global context. you cannot use String.interpolate inside a method and use local variables there. have fun messju