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.

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.