Ruby在处理边界值时,如何确保边缘情况下的数据准确性?
- 内容介绍
- 文章标签
- 相关推荐
本文共计336个文字,预计阅读时间需要2分钟。
Ruby 有一些边缘情况非常难以解释,因为解析会带来一些有趣的问题。例如:
1. 赋值时,`nil` 被当作 `false`。
2.混入(Mixin)可能导致意外的继承。
如果你知道更多,请添加到列表中。+def+foo+5end
ruby有一些边缘情况很难解释,因为解析会带来一些有趣的问题.我在这里列出其中两个.如果你知道更多,那么添加到列表中.def foo 5 end # this one works if (tmp = foo) puts tmp.to_s end # However if you attempt to squeeze the above # three lines into one line then code will fail # take a look at this one. I am naming tmp2 to # avoid any side effect # Error: undefined local variable or method ‘tmp2’ for main:Object puts tmp2.to_s if (tmp2 = foo)
这是另一个.
def x 4 end def y x = 1 if false x + 2 end # Error: undefined method `+' for nil:NilClass puts y
但是,如果您注释掉x = 1行,如果为false,则代码将正常工作.
你的第二个例子并不出人意料.即使x从未被赋值,它也会通知解释器你在下一行中讨论变量x而不是函数x. Ruby在确定名称的上下文时会尝试相当松散,但它会在可用的地方获取线索.它有助于具体,例如:
def y x = 1 if false x() + 2 end
本文共计336个文字,预计阅读时间需要2分钟。
Ruby 有一些边缘情况非常难以解释,因为解析会带来一些有趣的问题。例如:
1. 赋值时,`nil` 被当作 `false`。
2.混入(Mixin)可能导致意外的继承。
如果你知道更多,请添加到列表中。+def+foo+5end
ruby有一些边缘情况很难解释,因为解析会带来一些有趣的问题.我在这里列出其中两个.如果你知道更多,那么添加到列表中.def foo 5 end # this one works if (tmp = foo) puts tmp.to_s end # However if you attempt to squeeze the above # three lines into one line then code will fail # take a look at this one. I am naming tmp2 to # avoid any side effect # Error: undefined local variable or method ‘tmp2’ for main:Object puts tmp2.to_s if (tmp2 = foo)
这是另一个.
def x 4 end def y x = 1 if false x + 2 end # Error: undefined method `+' for nil:NilClass puts y
但是,如果您注释掉x = 1行,如果为false,则代码将正常工作.
你的第二个例子并不出人意料.即使x从未被赋值,它也会通知解释器你在下一行中讨论变量x而不是函数x. Ruby在确定名称的上下文时会尝试相当松散,但它会在可用的地方获取线索.它有助于具体,例如:
def y x = 1 if false x() + 2 end

