1

I'm using the Learn Game Programming with Ruby book and I'm trying to just execute the sample code.

I get the following error, using the sample code.

❯ ruby WhackARuby/WhackARuby_1/whack_a_ruby.rb                                                                                                           code
/Users/noahclark/.rvm/gems/ruby-2.2.1/gems/gosu-0.10.4/lib/gosu/patches.rb:40:in `initialize': Cannot open file ruby.png (RuntimeError)
        from /Users/noahclark/.rvm/gems/ruby-2.2.1/gems/gosuu0.10.4/lib/gosu/patches.rb:40:in `initialize'
        from WhackARuby/WhackARuby_1/whack_a_ruby.rb:15:in `new'
        from WhackARuby/WhackARuby_1/whack_a_ruby.rb:15:in `initialize'
        from WhackARuby/WhackARuby_1/whack_a_ruby.rb:70:in `new'
        from WhackARuby/WhackARuby_1/whack_a_ruby.rb:70:in `<main>'

The sample code looks like this:

require 'gosu'

class WhackARuby < Gosu::Window
  def initialize
    super(800, 600)
    self.caption = 'Whack the Ruby!'
    @image = Gosu::Image.new('ruby.png')
  end
end

Any thoughts on what could be going on here? I've tried changing the offending line to @image = Gosu::Image.new('./ruby.png') for example and that didn't help.

I doubt this is the cause, but my ruby version is ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin14]

EDIT includes file path: screenshot of tree command

4

2 回答 2

1

问题总是因为文件不存在于您认为的位置。

有很多方法可以引用文件。File文档有expand_path, realpath, , 所有这些absolute_path都可以很容易地根据绝对或相对路径引用文件,并且相对于当前运行的文件、应用程序或特定目录。他们的示例中介绍了如何使用它们。

确保您知道代码认为它是当前工作目录的目录和/或文件所在的位置很重要。第一个在使用相对路径时很重要,第二个是如果您不想关心当前路径并且知道文件始终存在于某个位置。

而且,还有一种情况是文件名与您认为的不同,或者它甚至不存在。

于 2015-12-18T19:42:38.033 回答
0

在我的情况下,解决方案是使用更明确的文件路径:

Gosu::Image.new("#{__dir__}/ruby.png")
于 2021-04-09T09:26:51.353 回答