Delayed quote expansion

I’m sure the answer to this will seem simple once I see it. Right now
it eludes me.

How can one have a string object like this…

a = ‘#{some_value}’

and have it get evaluated as a double quoted string (with the value for
some_value being automatically replaced) at a later time?

I would prefer that it is evaluated in context from which it is called.

I would like to do something like this…

def func(param)
test = 42
puts param.quote_substitution
end

func(‘my number is #{test}’) #=> “my number is 42”

_Kevin

On Jan 18, 2006, at 12:29 AM, Kevin O. wrote:

func(‘my number is #{test}’) #=> “my number is 42”
How about:

template = lambda { |x| "my number is: #{x}" }

# some time passes

template.call(42)	# "my number is: 42"

Gary W.

On 2006.01.18 14:29, Kevin O. wrote:

I would prefer that it is evaluated in context from which it is called.

I would like to do something like this…

def func(param)
test = 42
puts param.quote_substitution
end

func(‘my number is #{test}’) #=> “my number is 42”

You can delay evaluation like this:

string = ‘"#{foo}"’

value = eval string # Add a binding if you want

_Kevin

E

Lots of good responses here, but the one that turns out to be the
easiest is…

def func(param)
some_value = 42
value = eval %Q{%Q{#{param}}}
end

func(‘my number is #{some_value}’) #=> ‘my number is 42’

_Kevin

On 1/18/06, Kevin O. [email protected] wrote:
[snip]

I would like to do something like this…

def func(param)
test = 42
puts param.quote_substitution
end

func(‘my number is #{test}’) #=> “my number is 42”

Try this:

class String
def evaluate(*args)
eval inspect.gsub(/\#/, ‘#’), *args
end
end

def func(str)
x = 42
str.evaluate(binding)
end

puts func(‘the answer is #{x}’)

Paolo

James G. wrote:

What you really want here is ERB:

A good suggestion, but I would rather avoid unnecessary dependencies if
there is an adequate pure ruby way to do it.

_Kevin

On Jan 18, 2006, at 6:48 AM, Kevin O. wrote:

Lots of good responses here, but the one that turns out to be the
easiest is…

def func(param)
some_value = 42
value = eval %Q{%Q{#{param}}}
end

func(‘my number is #{some_value}’) #=> ‘my number is 42’

What you really want here is ERB:

require “erb”
=> true

def expand( template )
some_value = 42
ERB.new(template).result(binding)
end
=> nil

expand “My number is <%= some_value %>.”
=> “My number is 42.”

James Edward G. II

Bob S. wrote:

erb is pure Ruby. It is part of the standard library, so every Ruby
installation has it.

So it is, my bad.

Kevin O. wrote:

James G. wrote:

What you really want here is ERB:

A good suggestion, but I would rather avoid unnecessary dependencies if
there is an adequate pure ruby way to do it.

erb is pure Ruby. It is part of the standard library, so every Ruby
installation has it.