我有一个这样的课程
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
我想为每个属性调用setter。所以,我试过这个(因为你明白我想要的)
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
那么,如何为动态属性调用setter?
P / s:使用Ruby 1.8.7和Rails 2.3.5 谢谢。
答案 0 :(得分:1)
你应该致电
a.send "#{attr}=", 1
a.save!
答案 1 :(得分:0)
你可以试试这个
def set_attributes(*attributes)
attributes.each {|attribute| self.send("#{attribute}=", 1)}
end