views:

52

answers:

2

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

A: 

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.

Chuck
Wouldn't the string with the name of the instance variable I want to set be "username_new"? I tried putting "username_new" there and I got an error.
James Testa
@James Testa: No, the variable `username_new` references an instance of User, not a String. The error you got was probably along the lines of "This is not a valid name for an instance variable." Whatever instance variable in User represents the name is what you'd want to use there.
Chuck
@Chuck: Boy, I'm still confused. What I am trying to do is create a bunch of users with different user names using a for loop. Is username_new an instance variable? Or in this case would "username" be an instance variable?
James Testa
+3  A: 

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.

Wayne Conrad
@Wayne Conrad - Yup, this is all I needed. I actually had this, but because there was a bug in the parameters I was using for User.create(params), the users weren't getting created. So I came across instance_variable_set, thinking that would fix the problem, when in reality there was just a bug in my code :-) Thanks again!
James Testa
@james Testa, You're welcome! By the way, if you use `create!` instead of `create`, you'll get a nice exception if it doesn't get created.
Wayne Conrad