String interpolation method?

J

John Carter

Ok, I'm being stupid probably...

But I can't spot a method to do string interpolation.

I have a string...

a = 'bra#{c}ket'

The variable c isn't available at the stage of setting that up. Hence
the use of '' instead of "".

The variable will be available later....

At that stage I want to do something like...

c=' see '
a.interpolate

The closest I can get is a bit fugly...

eval "\"#{a}\""
=> "bra see ket"

Any better way?

Thanks,


John Carter Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : (e-mail address removed)
New Zealand
 
J

James Gray

Ok, I'm being stupid probably...

But I can't spot a method to do string interpolation.

I have a string...

a = 'bra#{c}ket'

The variable c isn't available at the stage of setting that up.

You want a templating solution, like the ERb code that ships with Ruby:

#!/usr/bin/env ruby -wKU

require "erb"

template = ERB.new("bra<%= c %>ket")

# and later...
c = "c"
p template.result

__END__

Hope that helps.

James Edward Gray II
 
Y

yermej

Ok, I'm being stupid probably...

But I can't spot a method to do string interpolation.

I have a string...

a = 'bra#{c}ket'

The variable c isn't available at the stage of setting that up. Hence
the use of '' instead of "".

The variable will be available later....

At that stage I want to do something like...

c=' see '
a.interpolate

The closest I can get is a bit fugly...

eval "\"#{a}\""
=> "bra see ket"

Any better way?

Thanks,

John Carter Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : (e-mail address removed)
New Zealand

I would do it thusly:

a = "bra%sket"
c = ' see '
a % c
=> "bra see ket"
 
G

Guby

Not that it is a lot nicer, but just another solution... and a little
bit on side of what you wanted, but:
=> "bra see ket"

:)
 
T

Trans

If you want it to look even nicer, write it like:
a = lambda{|c| "bra#{c}ket"}
a[" see "]
=> "bra see ket"

The only trouble here is that you get the binding of where you defined
the lambda, rather than the one in which you ultimately evaluate it
in.

With 1.9 I think we can use instance_exec to handle that however --
that being the case, the String::interpolate method I demoed above
could be improved.

T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top