动态获取变量值
我有以下类,
class User
attr_accessor :name, :age, :address
def initialize()
self.name = "new user"
self.age = 19
self.address = "address"
end
end
如果有一个方法来获取属性的指定值,我想要什么。意味着,我有另一种方法来获取上述类中的所有方法名称
methods = self.public_methods(all = false)
,并且我可以从中获取方法名称(我的意思是名称的 getter 等..),并且我想要一种传递该方法名称的方法(我有它作为字符串)并获取方法的返回值
例如:
当我传递“名称”作为方法名称时,我应该能够获取“新用户”作为值
希望我清楚地表达了我的问题,提前感谢
**请注意,我必须使用这种方式,因为我的班级有很多属性并且它有很多继承的类。因此单独访问每个属性是不可能的:D
I have the following class
class User
attr_accessor :name, :age, :address
def initialize()
self.name = "new user"
self.age = 19
self.address = "address"
end
end
What I want if to have a method to get the assigned values to the attributes. Means, I have another method to get all the method names inside the above class
methods = self.public_methods(all = false)
and I can get the method name from that (I mean the getter of name etc..) and I want a way to pass that method name (which I have it as string) and get the return value of the method
Ex:
when I pass 'name' as the method name I should be able to get 'new user' as the value
hope I made my question clear, thanks in advance
** Please note, i have to use this way as my class has so many attributes and it has so many inherited classes. So accessing each and every attr individually is not possible :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是
send
的用途:如果您没有访问器方法,则使用
instance_variable_get
是另一种选择:使用
public_methods
获取属性列表可能很危险,具体取决于您如何确定要调用哪些方法。相反,您可以创建自己的类方法,该方法既定义访问器又存储属性名称以供将来使用:That’s what
send
is for:Using
instance_variable_get
is another option if you don’t have an accessor method:Using
public_methods
to get a list of attributes could be dangerous, depending on how you determine which methods to call. Instead, you could create your own class method which both defines the accessor and stores the attribute name for future use: