简体   繁体   English

如何在 ruby 中动态初始化实例变量?

[英]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.所以@var1 = site.site_1_location,@var2 = site.site_2_location,等等。

Mocking @sites data: Mocking @sites 数据:

@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您可以使用instance_variable_set设置实例变量

@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"

Using #send might help使用#send可能会有所帮助

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

eval(code)

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!尽管如此,Imram Ahmad ( https://stackoverflow.com/a/66002619/14485176 ) 建议的代码解决方案是解决您问题的更好方法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM