ruby边缘情况

ruby边缘情况,第1张

概述ruby有一些边缘情况很难解释,因为解析会带来一些有趣的问题.我在这里列出其中两个.如果你知道更多,那么添加到列表中. def foo 5end# this one worksif (tmp = foo) puts tmp.to_send# However if you attempt to squeeze the above# three lines into one l ruby有一些边缘情况很难解释,因为解析会带来一些有趣的问题.我在这里列出其中两个.如果你知道更多,那么添加到列表中.

def foo  5end# this one worksif (tmp = foo)  puts tmp.to_send# 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:Objectputs tmp2.to_s if (tmp2 = foo)

这是另一个.

def x  4enddef y  x = 1 if false   x + 2end# Error: undefined method `+' for nil:NilClassputs y

但是,如果您注释掉x = 1行,如果为false,则代码将正常工作.

解决方法 在您的第一个示例中,tmp2在到达if语句之前未分配.

你的第二个例子并不出人意料.即使x从未被赋值,它也会通知解释器你在下一行中讨论变量x而不是函数x. Ruby在确定名称的上下文时会尝试相当松散,但它会在可用的地方获取线索.它有助于具体,例如:

def y  x = 1 if false  x() + 2end
总结

以上是内存溢出为你收集整理的ruby边缘情况全部内容,希望文章能够帮你解决ruby边缘情况所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1247469.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存