Forum: Ruby on Rails Interpolation

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
northband (Guest)
on 2009-02-18 06:57
(Received via mailing list)
Hi -

I am adding a series of records within a for loop using i as my
counter.  Rather than hard code the model attributes I would like to
dynamically create them.

Here's what I'm trying to do:

I have several fields on my example model named such as:
spec_1_english
spec_2_english
etc...

This is what I would like to do - create these attributes dynamically
using my counter.

for i in (0..2)
    example.spec_#{i}_english = "test value"
    l.save
end

Any help appreciated.

Thanks!
Craig D. (Guest)
on 2009-02-18 07:15
(Received via mailing list)
You could use #send. Try something like this:

(0..2).each do |i|
  example.send("spec_#{i}_english=", "test value")
  l.save
end

Do you really want l.save instead of example.save, though? Maybe there's
some context missing from your code snippet.

Regards,
Craig
northband (Guest)
on 2009-02-18 07:27
(Received via mailing list)
Excellent - this worked great.  Another tool for me to use.  You're
correct l. was an error on my part in my snippet.

Thanks Craig
This topic is locked and can not be replied to.