From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2001-10-28T14:19:30+09:00 Subject: [ruby-talk:23666] Re: How to get a String to interpolate itself? In article , Phil Tomson wrote: >In article <3BDB73A2.7B1C14FF@path.berkeley.edu>, > wrote: >>Phil Tomson wrote: >>> > >It works, but it seems a bit kludgy. Certainly not very OO. It seems to >me that we need a String#interpolate method. >str.interpolate => "This is the value of var: 3" > To critique mey own suggestion: There probably is no 'interpolate' method defined for the String class because of the scoping problem: It would be interpolated in what context? For example, let's say we define String#interpolate: class String def interpolate eval "\"#{self.to_s}\"" end end Now try: var = 99 bstr = 'now try this: #{var}' bstr.interpolate You'll get an error message about 'var' being an undefined variable - it's not defined with in the scope of String where it is being eval'ed. So, in order to get it to work you would have to pass a binding in to the interpolate method: class String def interpolate(bind) eval ("\"#{self.to_s}\"",bind) end end var = 99 bstr = 'now try this: #{var}' p bstr.interpolate( binding()) Now it will work, but it's a bit nasty passing in the binding, couldn't there be some bad consequences of this? Any other ideas? (maybe we could just pass in a list of variables and their values to interpolate for). Phil