From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2001-10-28T13:39:23+09:00 Subject: [ruby-talk:23665] Re: How to get a String to interpolate itself? In article <3BDB73A2.7B1C14FF@path.berkeley.edu>, wrote: >Phil Tomson wrote: >> >> I'm trying to read lines from a file that might contain something like: >> >> Here is a line with a variable to interpolate: #{var} >> >> Now when I read it in like: >> >> var = 99 >> File.foreach("junk.rbt") {|line| >> puts line >> } >> >> of course I get the same line in the file with the #{var} in it. >> I'd like to get: >> Here is a line with a variable to interpolate: 99 >> >> I suspect there must be a way to do this since using "" causes >> interpolation, how can I get an existing String to interpolate itself? >> >> Phil > >How's this? > > var = 3 > str = 'This is the value of var: #{var}' > puts eval "\"#{str}\"" > # ==> This is the value of var: 3 > > # also: > puts eval '"' + str + '"' > # ==> This is the value of var: 3 > 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" Speaking of string interpolation and double quotes.... When you do: "this is a string".type => String Which means that double quotes are kind of constructor for strings - with the added functionality of interpolating Ruby expressions which are between '#{' and '}'. Where is this functionality of double quotes defined (as in which class is it defined in?)? Is it possible that String#interpolate could somehow call this already-existing functionality instead of using the eval trick shown above? Are double quotes actually a method on a class or something built-in at a deeper level? Phil