From: Niklas Frykholm Date: 2002-02-06T20:41:52+09:00 Subject: Re: expanding variables in strings [Martin Maciaszek]: > I have a long list of variables that gets used at several places in > my program. I figured that it might be a good idea to put the names > of those variables in an array. So I ended up with the following: > > %w{ foo bar baz}.collect { |x| "'\#{" + x + "}'"}.join(", ") > --> "'#{foo}', '#{bar}', '#{baz}'" > > This returns a nice string that I would be otherwise cut&pasting all > over my program. But now I need to expand those variables. I've looked > up the String class but couldn't find anything useful (except trying > to rewrite those expensions from scratch) You could use eval("%Q{#{str}}") to eval str as a quoted string (provided that {} are balanced in the string). But I would probably rewrite this as a function instead, as below: def vars(b) %w{foo bar baz}.collect {|s| "'#{eval(s,b)}'"}.join(', ') end foo = 3 bar = 'hallo' baz = 'bazzy' puts vars(binding) // Niklas