我有一个我写的小红宝石应用程序,它是一个字谜搜索器。它是用来学习红宝石的,但我想把它放在网上供个人使用。我对 Rails 有一些经验,这里的很多人都推荐过 Sinatra。我都很好,但我找不到任何关于如何使用文本文件而不是数据库的信息。
该应用程序非常简单,根据单词列表的文本文件进行验证,然后找到所有字谜。我一直假设这应该很简单,但我坚持将该文本文件导入 Rails(或者如果我选择这种方式,则为 Sinatra)。在 Rails 项目中,我已将文本文件放在lib
目录中。
不幸的是,即使路径在 Rails 中看起来是正确的,我还是得到了一个错误:
no such file to load -- /Users/court/Sites/cvtest/lib/english.txt
(cvtest
是 rails 项目的名称)
这是代码。它本身就很好用:
file_path = '/Users/court/Sites/anagram/dictionary/english.txt'
input_string = gets.chomp
# validate input to list
if File.foreach(file_path) {|x| break x if x.chomp == input_string}
#break down the word
word = input_string.split(//).sort
# match word
anagrams = IO.readlines(file_path).partition{
|line| line.strip!
(line.size == word.size && line.split(//).sort == word)
}[0]
#list all words except the original
anagrams.each{ |matched_word| puts matched_word unless matched_word == input_string }
#display error if
else
puts "This word cannot be found in the dictionary"
end