简体   繁体   English

Ruby String访问对象属性

[英]Ruby String to access an object attribute

I have a text file (objects.txt) which contains Objects and its attributes. 我有一个文本文件(objects.txt),其中包含对象及其属性。 The content of the file is something like: 该文件的内容类似于:

Object.attribute = "data"

On a different file, I am Loading the objects.txt file and if I type: 在另一个文件上,我正在加载objects.txt文件,如果键入:

puts object.attribute it prints out data puts object.attribute放出data

The issue comes when I am trying to access the object and/or the attribute with a string. 当我尝试使用字符串访问对象和/或属性时,就会出现问题。 What I am doing is: 我正在做的是:

var = "object" + "." + "access" puts var

It prints out object.access and not the content of it "data" . 它打印出object.access而不是它的内容"data"

I have already tried with instance_variable_get and it works, but I have to modify the object.txt and append an @ at the beginning to make it an instance variable, but I cannot do this, because I am not the owner of the object.txt file. 我已经尝试过instance_variable_get ,并且可以使用,但是我必须修改object.txt并在开头添加一个@使其成为实例变量,但是我不能这样做,因为我不是object.txt的所有者文件。

As a workaround I can parse the object.txt file and get the data that I need but I don't want to do this, as I want take advantage of what is already there. 作为一种解决方法,我可以解析object.txt文件并获取所需的数据,但是我不想这样做,因为我想利用已有的资源。

Any suggestions? 有什么建议么?

Yes, puts is correctly spitting out "object.access" because you are creating that string exactly. 是的,puts正确吐出了“ object.access”,因为您正在精确地创建该字符串。

In order to evaluate a string as if it were ruby code, you need to use eval() 为了评估字符串是否就像红宝石代码,您需要使用eval()

eg: 例如:

var = "object"  +    "."  + "access"
puts eval(var)
=> "data"

Be aware that doing this is quite dangerous if you are evaluating anything that potentially comes from another user. 请注意,如果您要评估可能来自其他用户的任何内容,则这样做非常危险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM