Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 从终端创建字典。如何在txt文件中插入单词?_Ruby_Terminal - Fatal编程技术网

Ruby 从终端创建字典。如何在txt文件中插入单词?

Ruby 从终端创建字典。如何在txt文件中插入单词?,ruby,terminal,Ruby,Terminal,我正在尝试从此命令获取此输出: cat /usr/share/dict/words 并将其放入文本文件中。我最终想要创建一个类方法,它接受一个字符串,比如(“cat,dog”,“xysafjkdfj”),并查看其中哪个单词不在字典中。我该怎么做 我做到了: cat /usr/share/dict/words >> dictionary.txt 还有别的办法吗 基本上,我正在尝试编写一个Ruby程序,检查给定给该类的某些单词是否包含在这本词典中。您可能想提及您打算如何使用它,因为g

我正在尝试从此命令获取此输出:

cat /usr/share/dict/words
并将其放入文本文件中。我最终想要创建一个类方法,它接受一个字符串,比如(“cat,dog”,“xysafjkdfj”),并查看其中哪个单词不在字典中。我该怎么做

我做到了:

cat /usr/share/dict/words >> dictionary.txt
还有别的办法吗


基本上,我正在尝试编写一个Ruby程序,检查给定给该类的某些单词是否包含在这本词典中。

您可能想提及您打算如何使用它,因为
grep
可以做您想做的事,例如
grep'^word$'/usr/shared/dict/words

尽管如此,您所要做的只是将所有文本拼凑起来并在换行符上拆分(\n)。然后,您可以检查数组是否包含您要查找的单词

举个简单的例子

dictionary = `cat /usr/share/dict/words`.split("\n").map(&:downcase)
dictionary.include? "foo"
# => true
dictionary.include? "akjsdfakjd"
# => false
更具ruby风格的示例(未测试)


/usr/share/dict/words
已经是一个文本文件。请详细解释一下您到底需要什么。将
cat/usr/share/dict/words
放在勾号中与将cat/user/share/dict/words放在irb中有什么区别?后面的勾号允许您执行shell命令并从ruby代码中获取输出。我在这里只是用它作为一种快速而肮脏的方式来获取文字。
class Dictionary
  attr_reader :words

  def initialize(src = '/usr/share/dict/words')
    @words = File.read(src).split("\n").map(&:downcase)
  end

  # you could probably even delegate this
  def include?(word)
    words.include? word
  end
end

dict = Dictionary.new
dict.include? "foo"
# => true