String interpolation

T

Thomas Worm

a = 5
b = "#{a}"
puts b

a = 6
puts b

Returns:
5
5

which is clear to me, why. But is there a way to define such a string and
interpolate it at a later time?

Thomas
 
S

Stefan Rusterholz

Thomas said:
a = 5
b = "#{a}"
puts b

a = 6
puts b

Returns:
5
5

which is clear to me, why. But is there a way to define such a string
and
interpolate it at a later time?

Thomas

a = 5
b = proc { "a is now: #{a}" }
def b.to_s; call; end
puts b # !> a is now: 5
a = 6
puts b # !> a is now: 6

Enjoy

Regards
Stefan
 
T

Thomas Worm

a = 5
b = proc { "a is now: #{a}" }
def b.to_s; call; end
puts b # !> a is now: 5
a = 6
puts b # !> a is now: 6

Many thanks for the quick help !!!
Thomas
 
X

Xavier Noria

a = 5
b = "#{a}"
puts b

a = 6
puts b

Returns:
5
5

which is clear to me, why. But is there a way to define such a
string and
interpolate it at a later time?

You normally use a templating system, for example:

require 'erb'

b = ERB.new("a is <%= a %>")

a = 5
puts b.result(binding) # -> a is 5

a = 6
puts b.result(binding) # -> a is 6

-- fxn
 
P

Phlip

Thomas said:
a = 5
b = "#{a}"
puts b

a = 6
puts b

Returns:
5
5

which is clear to me, why. But is there a way to define such a string and
interpolate it at a later time?

You are asking how to do a "block closure". Study that, because it's a major
Ruby topic and a very good design technique. I have not yet found a way to
over-use or abuse blocks in Ruby!

A 'lambda' is one of the block systems that can bond with the variables
around it. So stick your string evaluator into a lambda, and call it:
=> "6"

Block closures are a very good design technique because a has a very limited
scope over a very long lifespan. We could have stored that q and used it
later. So a becomes very encapsulated.
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top