为什么我不能运行这个 ruby​​ 文件?

时间:2021-01-27 23:39:20

标签: ruby

我在 Ubuntu 上。我有一个看起来像这样的 ruby​​ 文件。

class Hangman
  def initialize
    @letters = ('a'..'z').to_a
    @word = words.sample
  end

  def words
    [
      ['cricket', 'A game played by gentlemen'],
      ['Something', 'A cool sentence'],
      ['house', 'This is getting tiring'],
      ['ruby', 'Science has created'],
      ['blah ', 'This is the last one'],
    ]
  end

  def begin
    #ask user for a letter
    puts `new game started... your clue is #{ @word.first }`
    guess = gets.chomp

    puts "You guessed #{guess}"
  end

end

game = Hangman.new
game.begin

这个 ruby​​ 文件在我当前的目录中被称为“play.rb”。我检查我当前的工作目录,我得到

/home/ray/Documents/Projects/hangman-game

现在我想通过这样做来运行这段代码

ruby play.rb

但它不起作用。这是我得到的错误。

play.rb:19:in ``': No such file or directory - new (Errno::ENOENT)
        from play.rb:19:in `begin'
        from play.rb:28:in `<main>'

我确定文件在那里。我不明白为什么它不起作用。有没有人看到这个问题?另外我使用的是 Ruby 3.0。

3 个答案:

答案 0 :(得分:3)

在第 19 行,您使用反引号 `` 而不是引号。反引号在 shell 中执行字符串并将结果作为字符串返回:尝试用 pwdls 替换它。但在这里您需要双引号 ""

错误消息中有一些线索可以帮助您指出问题所在:

  • 行号标识行,
  • 反引号运算符被标识为发生错误的方法调用,并且
  • “No such file or directory - new (Errno::ENOENT)”表示系统正在尝试查找名为 new 的命令——该字符串中的第一个单词。

答案 1 :(得分:1)

替换:

puts `new game started... your clue is #{ @word.first }`

致:

puts "new game started... your clue is #{ @word.first }"

答案 2 :(得分:1)

您对要显示的消息使用反引号,但在被解释为命令评估的 ruby​​ 中,请改用双引号。

改变这个:

`new game started... your clue is #{ @word.first }`

为此:

"new game started... your clue is #{ @word.first }"
相关问题