Reputation: 16081
I'm quite new to Ruby so I hope this question isn't already answered elsewhere. But I've been searching here and on the internet for quite a while with no results yet.
I am reading in a bunch of file paths from a text file. Each file path has some expressions (i.e. #{...} ) embedded into the string. For instance:
input = 'E:/files/storage/#{high_or_low}/#{left_or_right}/*.dll'
Anyways, I want to evaluate those strings as if they were ruby code and get those expressions replaced. For instance:
def high_or_low
'low'
end
def left_or_right
'left'
end
# It represents a file path on the disk drive
input = 'E:/files/storage/#{high_or_low}/#{left_or_right}/*.dll'
puts input
# Now how do I execute this 'input' string so that it behaves as if it was defined with quotes?
result = eval input
puts result
I purposefully put single quotes around the original input string to show that when the string comes in off the disk, the expression embedded in the string is unevaluated. So how do I evaluate the string with these expressions? Using eval as shown above doesn't seem to work. I get this error:
test_eval.rb:15: compile error (SyntaxError)
test_eval.rb:15: syntax error, unexpected tIDENTIFIER, expecting $end
Thanks
Upvotes: 0
Views: 338
Reputation: 16081
Ah found it. pst got me started in the correct direction. So once I wrapped the input variable in quotes like this, it worked:
result = eval '"' + input + '"'
puts result
=> E:/files/storage/low/left/*.dll
Upvotes: 0
Reputation: 19879
pst pointed you to why it's failing. As an alternative, which may or may not work depending on what your data looks like... but if it's simple strings with method names (and in particular doesn't contain nested "}"'s...
result = input.gsub(/\#{(.*?)}/) {|s| send($1)}
puts result
Upvotes: 1