TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ruby statement modifiers behave differently than conditional statements

26 点作者 angilly超过 15 年前

5 条评论

aaronblohowiak超过 15 年前
I contend that if you are using defined? you are doing something wrong. local variables should be <i>local</i>. If you don't know what exists in the current scope, you are dealing with confusing code. Rails erb evaluation for partials makes this mistake, and creates a poor reimplementation of function calls where the function header is defined by the caller with the :locals =&#62;{} hash.
评论 #1019079 未加载
评论 #1019440 未加载
figgs超过 15 年前
The following is wrong. Only read the rest of this reply if you want to see how dumb I am.<p><i>This is not a bug.<p>"a = 5 unless defined? a" is not meant to be equivalent to this:<p><pre><code> unless defined? a a = 5 end </code></pre> It is supposed to be (and is) equivalent to this:<p><pre><code> a = unless defined? a 5 end*</code></pre>
评论 #1018952 未加载
评论 #1018895 未加载
tmm1超过 15 年前
<p><pre><code> &#62;&#62; if false &#62;&#62; a = 1 &#62;&#62; end &#62;&#62; defined? a =&#62; "local-variable" &#62;&#62; a =&#62; nil</code></pre>
评论 #1019271 未加载
Locke超过 15 年前
Yes, they are different. For example:<p><pre><code> def ex1 a = 5 if a puts "a: #{a}" end end def ex2 if a = 5 puts "a: #{a}" end end def ex3 puts "a: #{a}" if a = 5 end </code></pre> If we start with the code in ex1 and decide to shorten it, ex2 is okay (although some people don't care for assignment in a conditional because it could be confused for a typo). But, ex3 will raise an exception that 'a' has not been defined.<p>I've just internalized using the longer form when using assignment in a conditional.
评论 #1019102 未加载
rue超过 15 年前
I think the main part was already covered, but there is one important detail left uncorrected:<p>They are <i>expression</i> modifiers and conditional <i>expressions</i>. Everything in Ruby is an expression, not a statement.