【问题标题】:Can you use a part of string, read from text, as a variable in Ruby?您可以使用从文本中读取的字符串的一部分作为 Ruby 中的变量吗?
【发布时间】:2017-02-13 02:05:20
【问题描述】:

我正在尝试将文件(大约 200 个文件)中的一些文本解析到应用程序中,但我希望一些文本从变量中获取结果。这是一个例子。 我有一个名为“Description.txt”的文件。

文件中的文字是“放置#{@number} 地雷,造成#{@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."

有可能吗?

【问题讨论】:

  • 所以你的类为所有 200 个文件定义了所有实例变量

标签: ruby string file parsing variables


【解决方案1】:
@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

【讨论】:

  • 非常感谢,这样就可以了!这是我刚刚找到的 Sub 的另一种方法! @text.sub! '#{@number}', "#{@number}" @text.sub! '#{@damage}', "#{@damage}"
猜你喜欢
  • 2018-09-17
  • 1970-01-01
  • 2010-09-25
  • 2021-11-01
  • 2013-09-24
  • 2015-06-27
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多