3

I want to do something like:

4.times do |n|
  "member#{n}" = Fabricate(:user)
end

Calling member1, member2 etc.. would give me user instances. Is #send or #eval useful to my situation? Thanks for looking.

andy4thehuynh
  • 2,042
  • 3
  • 27
  • 37

1 Answers1

3

You cannot dynamically set local variables in this manner because what you are actually trying to do is set a String. Your code is interpreted as follows

"member1" = Fabricate(:user)

Which will raise a SyntaxError for unexpected = because you cannot set a String to anything.

You can however perform this operation with instance_variables like so:

4.times do |n|
  instance_variable_set("@member#{n}", Fabricate(:user))
end

Then access them with @member1,@member2, etc.

To answer your second question is no send and eval have no particular use in this case

engineersmnky
  • 25,495
  • 2
  • 36
  • 52