From: dm1 Date: 2005-04-22T19:39:33+09:00 Subject: Re: Clean way to dynamically expand string with "#{expression}"? And in a more OO way, you can use irb(main):001:0> class String irb(main):002:1> def interpolate(caller) irb(main):003:2> caller.instance_eval('"' + self + '"') irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> @toto = "afdgfd" => "afdgfd" irb(main):007:0> '123 #{@toto}'.interpolate(self) => "123 afdgfd" ciao Denis Neville Burnell wrote: > How about: > > irb(main):001:0> n = 1 > => 1 > irb(main):002:0> s = 'n = #{n}' > => "n = \#{n}" > irb(main):003:0> puts eval('"' + s + '"') > n = 1 > => nil > > -----Original Message----- > From: Taisuke Yamada [mailto:tyamadajp@list.rakugaki.org] > Sent: Friday, 22 April 2005 4:35 PM > To: ruby-talk ML > Subject: Clean way to dynamically expand string with "#{expression}"? > > Hi. > > I'm trying to find a clean way to expand string with "#{...}". > What I want to do is essentially as follows: > > data = 123 > expr = 'data = #{data}' > > puts dosomething(expr) > > and get 'data = 123' as a result. Actual content of 'expr' can be > anything, as long as it is a String object. > > I came up with following: > > puts eval(%Q{"#{expr.gsub('"', '\"')}"}) > > But this is ugly, and I'm wondering if there's some other, cleaner way > to do the same thing. > > Can anyone enlighten me? > > Best Regards, > -- > Taisuke Yamada