DollarChills
DollarChills

Reputation: 1086

How to initialise an instance variable dynamically in ruby?

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.

Upvotes: 0

Views: 91

Answers (3)

nbennke
nbennke

Reputation: 64

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!

Upvotes: 0

Imran Ahmad
Imran Ahmad

Reputation: 2927

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"

Upvotes: 2

obiruby
obiruby

Reputation: 419

Using #send might help

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

eval(code)

Upvotes: 0

Related Questions