0

Using interpolated strings is it possible to call multiple #{} within each other?

For example I want to create a variable and add a number onto the end. I also want to attach a result from a column in site, but also increment the number as well. What the best method of doing the below code?

@site.each do |site|
  1.upto(4) do |i|
    eval("@var#{i} = #{site.site_#{i}_location}", b)
  end
end

So @var1 = site.site_1_location, @var2 = site.site_2_location, etc.

1
  • This is a pure-Ruby question so you should have a Ruby tag and no Rails tag. Commented Feb 2, 2021 at 1:19

3 Answers 3

2

Mocking @sites data:

@sites = [OpenStruct.new(
  site_1_location: 'Japan',
  site_2_location: 'India',
  site_3_location: 'Chile',
  site_4_location: 'Singapore'
)]

You can use instance_variable_set to set the instance variable

@sites.each do |site|
  1.upto(4) do |i|
    instance_variable_set("@var#{i}", site.send("site_#{i}_location"))
  end
end

Now you can access the variables:

@var1 # returns "Japan"
@var2 # returns "India"
@var3 # returns "Chile"
@var4 # returns "Singapore"
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Much appreciated @imran-ahmad.
0

Using #send might help

code = "@var#{i} = site.send(:site_#{i}_location)"

eval(code)

Comments

0

Yes of cause, nesting of #{} is possible. Stupid example, but it shows the possibilties of nesting:

x = 1
y = 2
"abc_#{"#{x}_#{y if y > 1}"}"
# => 'abc_1_2'

Never the less, the solution for your code, suggested by Imram Ahmad (https://stackoverflow.com/a/66002619/14485176) is the better aproach to solve your problem!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.