开发者

dynamic variable names using Ruby's instance_variable_set

开发者 https://www.devze.com 2023-01-20 16:07 出处:网络
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

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开发者_JAVA百科 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?"?


Instance variables might be the wrong tool for the job. If all you want to do is create three users, then:

3.times do |i|
  User.create(:username => "user_#{i}")
end

If you need to retain the User objects for later use, then you can use an array:

@users = 3.times.map do |i|
  User.create(:username => "user_#{i}")
end

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消