使用 Ruby 的instance_variable_set 动态变量名
我正在尝试使用 instance_variable_set 创建一组具有不同实例名称的实例来更改实例名称,但我似乎无法将其更改为 工作。
for i in 0..3 do
username_str = String.new
username_str = 'user_' + i.to_s
username_new = User.new
username_new.instance_variable_set("@#{WHAT_DO_I_PUT_HERE?}", username_str)
username_new = User.create(:username => username_str)
end
我不明白的部分是我应该在instance_variable_set的第一个字段中放入什么,其中我有“WHAT_DO_I_PUT_HERE?”?
I'm trying to create a set of instances that have different instance names using instance_variable_set to change the instance name and I can't seem to get it to
work.
for i in 0..3 do
username_str = String.new
username_str = 'user_' + i.to_s
username_new = User.new
username_new.instance_variable_set("@#{WHAT_DO_I_PUT_HERE?}", username_str)
username_new = User.create(:username => username_str)
end
The part I can't figure out is what do I put in the first field of instance_variable_set where I have "WHAT_DO_I_PUT_HERE?"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实例变量可能不是适合这项工作的工具。如果您只想创建三个用户,那么:
如果您需要保留 User 对象以供以后使用,那么您可以使用数组:
之后
@users[0]
将检索第一个User 的实例,@users[1]
第二个,&c。Instance variables might be the wrong tool for the job. If all you want to do is create three users, then:
If you need to retain the User objects for later use, then you can use an array:
after which
@users[0]
will retrieve the first instance of User,@users[1]
the second, &c.您可以放置一个包含要设置的实例变量名称的字符串。或者,如果您没有这样的字符串,您可以跳过字符串插值并自己在其中写入实例变量的名称。
You would put a string containing the name of the instance variable you want to set. Alternatively, if you do not have such a string, you could just skip the string interpolation and write the name of the instance variable in there yourself.