我只是想知道这个语法记录在哪里:
1 > 2 || raise("error")我试着把它用作条件:
1 > 2 || p "test"但它不起作用:
SyntaxError: (irb):9: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
1 > 2 || p "test"
^
from C:/Ruby193/bin/irb:12:in `<main>'发布于 2012-04-05 01:32:20
你有的东西不能工作,因为你需要括号:
1 > 2 || p("test")请注意,or (and and) has a different precedence than &&/||将不需要括号即可工作(并且您所做的操作更具语义意义):
1 > 2 or p "test"就像unless一样
p "test" unless 1 > 2发布于 2012-04-05 01:26:31
这只是一种内联方式,意思是“如果条件为false,则引发错误”。||只是一个常见的OR运算符,并且使用short-circuit evaluation对表达式求值。然而,为了清楚起见,我更喜欢这样:
raise("error") unless 1 > 2发布于 2012-04-05 01:33:05
这两种执行都可以,问题是在p上排除了括号。从IRB运行代码
ruby-1.8.7-p302 :003 > 1 > 2 || raise("error")
RuntimeError: error
from (irb):3通过添加测试(“”),调用可以正常工作:
ruby-1.8.7-p302 :004 > 1 > 2 || p("test")
"test"https://stackoverflow.com/questions/10016234
复制相似问题