Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create Ruby variables with string interpolation [duplicate]

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.

like image 697
andy4thehuynh Avatar asked Sep 17 '26 08:09

andy4thehuynh


1 Answers

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

like image 58
engineersmnky Avatar answered Sep 19 '26 21:09

engineersmnky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!