2016-10-04 50 views
1

我想从文件(约200文件)的一些文本解析为一个应用程序,但我想一些文字来得到变量的结果。这是一个例子。 我收到了一个名为“Description.txt”的文件。您可以使用从文本中读取的字符串的一部分作为Ruby中的变量吗?

文件中的文字是这样的一个“放#{@}数与矿山#{@}损坏的损坏。”

@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." 

这可能吗?

+0

所以你的类是有所有的所有200个文件中定义 – Bijendra

回答

2
@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." 

在开始偏移

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

感谢很多实例变量,会做!这是另一种方式与我刚刚发现! @ text.sub! '#{@ number}',“#{@ number}” @ text.sub! '#{@ damage}',“#{@ damage}” –

相关问题