将 nil 强制转换为数字
这里发生了什么?
irb(main):001:0> a= nil
=> nil
irb(main):002:0> b = nil
=> nil
irb(main):003:0> a
=> nil
irb(main):004:0> a+b
NoMethodError: undefined method `+' for nil:NilClass
from (irb):4
from :0
irb(main):005:0> if a.nil? or b.nil?; a,b=0;end;
irb(main):006:0* c = a+b
TypeError: nil can't be coerced into Fixnum
from (irb):6:in `+'
from (irb):6
from :0
irb(main):007:0>
如何通过将 nil 转换为数字来安全地执行算术?
What is happening here??
irb(main):001:0> a= nil
=> nil
irb(main):002:0> b = nil
=> nil
irb(main):003:0> a
=> nil
irb(main):004:0> a+b
NoMethodError: undefined method `+' for nil:NilClass
from (irb):4
from :0
irb(main):005:0> if a.nil? or b.nil?; a,b=0;end;
irb(main):006:0* c = a+b
TypeError: nil can't be coerced into Fixnum
from (irb):6:in `+'
from (irb):6
from :0
irb(main):007:0>
How can you safely perform arithmetic by transforming nil to an number?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据为什么是 nil 而不是数字,您可以决定将 nil 视为 0 对您有好处;在这种情况下,你可以这样做:
当然,只有当你知道为什么你有一个 nil 而不是一个数字时,这才有意义......
Depending on why there's a nil instead of a number, you could decide that it's good for you to consider nil as 0; in that case, you can do something like:
This, of course, only makes sense if you know why you have a nil instead of a number...
为什么要添加
nil
?它被专门设计为表示缺少值的东西(注意:nil
不是0
)。如果您真正想要做的是将两个值设置为
0
(如果其中一个值当前nil
),那么您真正想要的是:上面代码中的错误是
a,b=0
部分,它仅将a
的值设置为0
- 它设置了b
到nil
因为左侧正在寻找两个值,而右侧只提供了一个(因此其他值被假定为nil
)。Why would you want to add
nil
? It's specifically designed to be something that represents the lack of a value (note:nil
is NOT0
).If what you're actually wanting to do is set both values to
0
if either is currentlynil
, then what you actually want is this:Your mistake in the code above was the
a,b=0
portion, which only sets the value ofa
to0
- it setsb
tonil
because the left hand side is looking for two values, and only one is provided on the right (so the others are assumed to benil
).您的并行分配 (
a, b = 0
) 会产生a=0
和b=nil
,即分配0
code> 到a
和nil
到b
,因为右侧只有一个值。你想要的是:
如果a.nil?或b.nil?; a = b = 0;结尾
c = a + b
显然,代码仍然有问题,因为当
a
或b
为零。Your parallel assignment (
a, b = 0
) results ina=0
andb=nil
, i.e. it assigns0
toa
andnil
tob
, because there is only one value on the right hand side.What you want is:
if a.nil? or b.nil?; a = b = 0; end
c = a + b
Obviously the code is still broken, since you overwrite any non-nil values of
a
andb
with 0 whena
orb
is nil.