I'm new to ruby so please excuse my ignorance :)
I just learned about eval
and I read about its dark sides.
what I've read so far:
so what I have to do is to read a file in which there are some text such as /e/ 3
which will replace each e
with a 3
after evaluation.
so here what i did so far:(working but..)
def evaluate_lines
result="elt"
IO.foreach("test.txt") do |reg|
reg=reg.chomp.delete(' ')
puts reg
result=result.gsub(eval(reg[0..2]),"#{reg[3..reg.length]}" )
p result
end
end
contents of the test.txt file
/e/ 3
/l/ 1
/t/ 7
/$/ !
/$/ !!
this only works because I know the length of the lines in the file.
so assuming my file has the following /a-z/ 3
my program would be not able to do what is expected from it.
Note
I tried using Regexp.new reg
and this resulted with the following /\/e\/3/
which isn't very helpful in this case.
simple example to the `Regexp
str="/e/3"
result="elt"
result=result.gsub(Regexp.new str)
p result #outputs: #<Enumerator: "elt":gsub(/\/e\/3/)>
i already tried stripping off the slashes but even though this wont deliver the desired result thus the gsub()
takes two parameters, such as this gsub(/e/, "3")
.
for the usage of the Regexp, I have already read Convert a string to regular expression ruby