ruby - How do I execute Date from a string? -
i trying read file has dynamic dates in such date.today
or (date.today - 1 )
, , perform code based on date requested.
if have string defined date in quotes works. when reading same string file not. there eval
function need use make work?
require 'date' #works abc = "something #{date.today}" puts abc # 2013-04-19 #does not work f = file.read("test.txt") f.each_line { |line| puts line ; words = line.split("\t") puts line }
contents of test.txt file:
something #{date.today} # #{date.today}
you're going have use eval
evaluate contents of each line read.
but since evaluating arbitrary code have trust not malicious code.
so, assuming trust file , lines:
require 'date' f = file.read("test.txt") f.each_line |line| puts eval("\"#{line}\"") end
notice double-quote wrapping, "piece of code" evaluating needs "valid" ruby string (which in turn contains code, wrap in quotes make appear actual double-quoted string.
this works if test.txt looks like:
hello, #{date.today} goodbye, #{date.today}
Comments
Post a Comment