1

我正在创建一个语法校正器应用程序。您输入俚语,它会返回一个正式的英语更正。支持的所有俚语都保存在数组中。当输入不支持的俚语时,我创建了一个看起来像这样的方法。

def addtodic(lingo)
  print"\nCorrection not supported. Please type a synonym to add '#{lingo}' the dictionary: "
  syn = gets.chomp
  if $hello.include?("#{syn}")
    $hello.unshift(lingo)
    puts"\nCorrection: Hello.\n"
  elsif $howru.include?("#{syn}")
    $howru.unshift(lingo)
    puts"\nCorrection: Hello. How are you?\n"   
  end
end

这有效,但仅在应用程序关闭之前。我怎样才能让它持续存在,以便它也修改源代码?如果我不能,我将如何创建一个包含所有案例的外部文件并在我的源代码中引用它?

4

1 回答 1

3

您需要将数组加载并存储在外部文件中。

如何将数组存储在ruby的文件中?与您正在尝试做的事情相关。

简短的例子

假设您有一个文件,其中每行有一个俚语

% cat hello.txt
hi
hey
yo dawg

以下脚本会将文件读入数组,添加一个术语,然后再次将数组写入文件。

# Read the file ($/ is record separator)
$hello = File.read('hello.txt').split $/

# Add a term
$hello.unshift 'hallo'

# Write file back to original location
open('hello.txt', 'w') { |f| f.puts $hello.join $/ }

该文件现在将包含一个带有您刚刚添加的术语的额外行。

% cat hello.txt
hallo
hi
hey
yo dawg

这只是将数组存储到文件的一种简单方法。检查此答案开头的链接以了解其他方式(对于不那么琐碎的示例,这将更好地工作)。

于 2012-08-09T20:41:50.773 回答