Possible Duplicate:
In Ruby, can you perform string interpolation on data read from a file?
I need to loop through a few ‘li’ elements:
for i in 1..5
Xpaths.getPath("location","elements")
end
Then, all xpaths are in an external file, so the value of such ‘elements’ variable is as follows:
{
"location":
{
"elements" :"//ul[@id='locations']/li[#{i}]/a"
}
}
The elements variable is read as a string, and [#{i}] is not replaced with values such as [1]. Is there a way to define a specific part of a string in an external file as a variable?
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:
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:
See also this related question: In Ruby, can you perform string interpolation on data read from a file?