1

I have a class like this

class A
    #this array of attributes is dynamic, just give example for understanding easier
    attributes = ['abc','S1','S2','S3']
    attributes.each do |e|
        attr_accessor e.to_sym
    end
end

I want to call setter for each attribute. So, I tried this (for you understand what I want)

a = A.new
attributes = ['abc','S1','S2','S3']
attributes.each do |attr|
    #I know the following command is wrong (because 'attr' is not a attribute of class A)
    a.attr = 1
end

So, how to call setter for dynamic attribute?

P/s: using Ruby 1.8.7 and Rails 2.3.5 Thank you.

0

2 Answers 2

2

You should call

a.send "#{attr}=", 1
a.save!
Sign up to request clarification or add additional context in comments.

1 Comment

And make sure attr is not from user input, or is whitelisted, otherwise you might run unintended methods.
0

You can try this

def set_attributes(*attributes)
    attributes.each {|attribute| self.send("#{attribute}=", 1)}
end

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.