下面的任务比较简单,我遇到了一个有趣的问题。开头的每个括号大小的块计算值为零,将Rubygame::Surface.new作为应该分配给@image的值。不幸的是,在我设置@rect的下一行中,它抛出一个NoMethodError,因为@image是零。
@image = (image unless image.nil?) or
(Rubygame::Surface.autoload(image_file) unless image_file.nil?) or
(Rubygame::Surface.autoload("#{@name}.png") unless @name.nil?) or
Rubygame::Surface.new([16, 16])
@rect = Rubygame::Rect.new [0, 0], [@image.width, @image.height]类似的测试运行在IRB中,正如预期的那样,所以我很确定'or‘语句的格式是正确的,但是我不知道为什么它不返回新的Surface,而其他所有东西都为零。
发布于 2010-09-11 11:16:34
Ruby中的or和and关键字具有非常、非常低优先级的。甚至低于赋值运算符=。因此,只需分别用||和&&替换它们(这两个绑定都比=更紧密),它应该会像您预期的那样工作。红宝石的操作符优先在这里列出。。
除此之外,我认为您的代码非常密集。考虑将其重构为如下内容,我认为这更好地表达了代码的意图。
@image = case
when image then image
when image_file then Rubygame::Surface.autoload(image_file)
when @name then Rubygame::Surface.autoload("#{@name}.png")
else Rubygame::Surface.new([16, 16])
end
@rect = Rubygame::Rect.new [0, 0], [@image.width, @image.height]发布于 2010-09-11 10:00:23
你试过更多的括号吗?
@image = ((image unless image.nil?) or
(Rubygame::Surface.autoload(image_file) unless image_file.nil?) or
(Rubygame::Surface.autoload("#{@name}.png") unless @name.nil?) or
Rubygame::Surface.new([16, 16]))发布于 2010-09-12 08:48:03
你为什么要使用RubyGame?Ruby的高苏游戏开发框架更快,更受欢迎。
https://stackoverflow.com/questions/3690508
复制相似问题