将 nil 强制转换为数字

发布于 2024-08-22 17:34:31 字数 481 浏览 10 评论 0原文

这里发生了什么?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

终陌 2024-08-29 17:34:31

根据为什么是 nil 而不是数字,您可以决定将 nil 视为 0 对您有好处;在这种情况下,你可以这样做:

c = (a || 0) + (b || 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:

c = (a || 0) + (b || 0)

This, of course, only makes sense if you know why you have a nil instead of a number...

电影里的梦 2024-08-29 17:34:31

为什么要添加nil?它被专门设计为表示缺少值的东西(注意:nil 不是 0)。

如果您真正想要做的是将两个值设置为 0(如果其中一个值当前 nil),那么您真正想要的是:

if a.nil? or b.nil?; a,b=0,0; end

上面代码中的错误是 a,b=0 部分,它仅将 a 的值设置为 0 - 它设置了 bnil 因为左侧正在寻找两个值,而右侧只提供了一个(因此其他值被假定为 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 NOT 0).

If what you're actually wanting to do is set both values to 0 if either is currently nil, then what you actually want is this:

if a.nil? or b.nil?; a,b=0,0; end

Your mistake in the code above was the a,b=0 portion, which only sets the value of a to 0 - it sets b to nil because the left hand side is looking for two values, and only one is provided on the right (so the others are assumed to be nil).

难理解 2024-08-29 17:34:31

您的并行分配 (a, b = 0) 会产生 a=0b=nil,即分配 0 code> 到 anilb,因为右侧只有一个值。

你想要的是:
如果a.nil?或b.nil?; a = b = 0;结尾
c = a + b

显然,代码仍然有问题,因为当 ab 为零。

Your parallel assignment (a, b = 0) results in a=0 and b=nil, i.e. it assigns 0 to a and nil to b, 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 and b with 0 when a or b is nil.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文