Ruby - 如何在 class 中设置动态属性值
Ruby - How to set value for dynamic attribute in class
我有一个class这样的
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
谢谢。
你应该打电话给
a.send "#{attr}=", 1
a.save!
你可以试试这个
def set_attributes(*attributes)
attributes.each {|attribute| self.send("#{attribute}=", 1)}
end
我有一个class这样的
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 谢谢。
你应该打电话给
a.send "#{attr}=", 1
a.save!
你可以试试这个
def set_attributes(*attributes)
attributes.each {|attribute| self.send("#{attribute}=", 1)}
end