0

可能重复:
在 Ruby 中,您可以对从文件中读取的数据执行字符串插值吗?

我需要遍历一些“li”元素:

for i in 1..5
  Xpaths.getPath("location","elements")      
end        

然后,所有的 xpath 都在一个外部文件中,所以这样的 'elements' 变量的值如下:

{ 
"location":
  {
  "elements"      :"//ul[@id='locations']/li[#{i}]/a"                                                           
  }
}              

elements 变量被读取为字符串,并且 [#{i}] 不会被替换为 [1] 等值。有没有办法将外部文件中字符串的特定部分定义为变量?

4

1 回答 1

0

If I understand your question correctly, you have some external data file in JSON format, whose structure has certain fields as XPath strings on which you would like to perform Ruby string interpolation.

The short answer is that yes, you can do this directly using, say Kernel#eval. There are also other options such as using erb. A solution using the simple "eval" route might look like this:

xpaths = JSON.load(File.read('my-xpaths.json'))
(1..5).each do |i|
  xpath = eval(xpaths['location']['elements'].to_json)
  # => "//ul[@id='locations']/li[1]/a"
end

Of course, using "eval" is fraught with peril since you are essentially executing code from another source, so there are many precautions you must take to ensure safety. A better approach might involve doing a simple regular expression replacement so that you can constrain the interpolation on the XPath item:

xpaths['location']['elements'] # => "//ul[@id='locations']/li[__INDEX__]/a"
xpath = xpaths['location']['elements'].gsub(/__INDEX__/, i.to_s)
# => "//ul[@id='locations']/li[1]/a"

See also this related question: In Ruby, can you perform string interpolation on data read from a file?

于 2012-09-21T16:28:46.040 回答