动态地向 Ruby 对象添加属性 [英] adding attributes to a Ruby object dynamically
问题描述
我创建了一个对象,我想根据一些条件检查向该对象添加一些属性.我怎样才能做到这一点?解释我想要什么:
I have an object created, and I want, based on some conditional check, to add some attributes to this object. How can I do this? To explain what I want:
A=Object.new
if(something happens)
{
#make A have another attibute say age
#& store something in A.age
}
推荐答案
首先,关于 ruby 的事情是它允许一种被 ruby 编码人员广泛使用的不同语法.大写标识符是类或常量(感谢 sepp2k 的评论),但您尝试将其设为对象.几乎没有人使用 {}
来标记多行块.
First of all the thing about ruby is that it allows a different syntax which is used widely by ruby coders. Capitalized identifiers are Classes or Constants (thanks to sepp2k for his comment), but you try to make it an object. And almost nobody uses {}
to mark a multiline block.
a = Object.new
if (something happens)
# do something
end
我不确定您的问题是什么,但我有一个想法,这就是解决方案:
I'm not sure what your question is, but I have an idea, and this would be the solution:
如果您知道该类可以具有哪些属性,并且它是有限的,那么您应该使用
If you know what attributes that class can have, and it's limited you should use
class YourClass
attr_accessor :age
end
attr_accessor :age
是:
def age
@age
end
def age=(new_age)
@age = new_age
end
现在您可以执行以下操作:
Now you can do something like this:
a = YourClass.new
if (some condition)
a.age = new_value
end
如果你想完全动态地完成,你可以这样做:
If you want to do it completely dynamically you can do something like this:
a = Object.new
if (some condition)
a.class.module_eval { attr_accessor :age}
a.age = new_age_value
end
这篇关于动态地向 Ruby 对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!