Jordan Kostov Jordan Kostov - 2 months ago 10
Ruby Question

Can you use a part of string, read from text, as a variable in Ruby?

I am trying to parse some text from files (about 200 files) into an app but I want some of the text to get result from variables. Here is an example.
I got a file called "Description.txt".

The text in the file is this one "Put #{@number} mines with #{@damage} damage."

@number = 3
@damage = 5
@text = File.read("Description.txt")

####When I print the variable I want to get this
echo @text

"Put 3 mines with 5 damage."


Is it possible?

Answer
@text = "This is what's in my file. Put #{@number} mines with #{@damage} damage. How now, brown cow?"

@number = 3
@damage = 5
regex = /Put #{@number} mines with #{@damage} damage./
@text[regex]
  #=> "Put 3 mines with 5 damage."

beginning at offset

$~.offset(0).first
  #=> 27