【问题标题】:undefined method `%' for false:FalseClass未定义的方法 `%' for false:FalseClass
【发布时间】:2017-05-21 16:53:14
【问题描述】:

错误 (undefined method '%' for false:FalseClass) 引用了这一行

   rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)

为什么会产生这个错误?它是编辑程序中一些默认代码的一部分,直到最近我才遇到这个问题。

【问题讨论】:

  • What is icon_index 这个错误告诉你要在布尔对象上使用#% 方法,所以为了让你的问题更清楚,请添加icon_index等于什么(简单示例),或者你从哪里得到的?

标签: ruby-on-rails ruby


【解决方案1】:

例如,如果您将a 初始化为nil,然后您想使用此值执行操作,您将看到undefined method '%' for nil:NilClass 错误,为避免此错误,您可以在之前检查该值是否为nil为了正常执行这样的操作,可能是:

puts (a % 1) if !a.nil?

这不会向您显示任何内容,因为 anil,它会以 true 响应您的 if 语句。

初始化为false 的值也会发生同样的情况,如果在这种情况下afalse,您将无法使用此对象执行% 操作,因为% 将是等待左侧的 integer 值:

a = false
puts (a % 1)
# => undefined method `%' for false:FalseClass (NoMethodError)

和以前一样,一个可能的解决方案是检查该值是否不是false

puts (a % 1) if a != false

您也可以使用if a,这可能意味着值不是nil 和/或不是false

puts a % 1 if a

或直接验证该值是否为integer 并且属于FixnumNumeric 类:

a = 1
puts a % 1 if a.class == Fixnum
# => 0
puts a % 1 if a.is_a? Fixnum
# => 0
puts a % 1 if a.is_a? Numeric
# => 0

在你的情况下,你可以这样做:

if icon_index
  rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
end

【讨论】:

  • 解释得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 2012-08-16
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多