Update variable value inside a string interpolation

$value = 10
str = “www.google.com/v1/cols?limit=100&offset=#{value}&data=q1
puts str # www.google.com/v1/cols?limit=100&offset=10&data=q1
$value = 30

puts str
expected out is : www.google.com/v1/cols?limit=100&offset=30&data=q1

how to achieve this ?
any help would be appreciated

# defined a method name str, not set a String value
def str(value)
  ['www.google.com/v1/cols?limit=100&offset=', value].join
end
str(10) #=> "www.google.com/v1/cols?limit=100&offset=10"
str(30) #=>"www.google.com/v1/cols?limit=100&offset=30"

The problem is that the string interpolation happens only once: when the Interpreter evaluates the string interpolation expression.

@cavalon gave you one alternative to interpolation.

Another solution is to make the evaluation of the interpolation dynamically. You can do that simply by defining a function with the string interpolation in it’s body, so each time the function is called, the Interpreter evaluates the expression again:

def url(offset)
  “www.google.com/v1/cols?limit=100&offset=#{offset}&data=q1”
end

puts url(10) # www.google.com/v1/cols?limit=100&offset=10&data=q1
puts url(30) # www.google.com/v1/cols?limit=100&offset=30&data=q1

There is another alternative worth knowing: The format operator %.

It combines a “template” with an object, and fills the “blanks” in the template with values obtained from the object.

Here is how you could use it for your example:

template = 'www.google.com/v1/cols?limit=100&offset=%s&data=q1'
puts template % 10
puts template % 30

The important thing to notice is that, in all solutions we have proposed, you are asking explicitly each time for a “string building”, dynamically.

Thank you so much !!, its helped me lot

1 Like

You would be better served with a object which contains the string, the value and interpolation and use a setter.