简体   繁体   中英

Why can't I run this ruby file?

I am on Ubuntu. I have a ruby file that looks like this.

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

This ruby file is called "play.rb" inside my current direcory. I check my current working directory and I get

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

Now I want to run this code by doing this

ruby play.rb

It doesn't work though. This is the error that I get.

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

I am sure the file is there. I don't understand why it's not working. Has anyone seen this issue? Also I am using Ruby 3.0.

On line 19 you're using backticks `` rather than a quote mark. The backticks execute the string in the shell and return the result as a string: try replacing it with pwd or ls . But here you want double-quotes "" .

There are some clues in the error message that help point you to where the problem is:

  • the line number identifies the line,
  • the backtick operator is identified as the method call where the error is occurring, and
  • "No such file or directory - new (Errno::ENOENT)" indicates that the system is trying to find a command called new -- the first word in that string.

Replace:

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

To:

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

You are using back-ticks for the message you want to display, but in ruby that is interpreted as a command evaluation, use double quote instead.

Change this:

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

For this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM