开发者

In Ruby, why is ( ) needed for 1 + rand(10)

rand 10 works but not 1 + rand 10. Why must it be 1 + rand(10)?

 > RUBY_DESCRIPTION
 => "ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-darwin10.4.0]" 

 > rand 10
 => 8 

 > (1 + rand 10)
SyntaxError: (irb):15: syntax error, unexpected tINTEGER, expecting keyword_do or '{' or '('
(1 + rand 10)
            ^
 from /Users/pet开发者_高级运维er/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'

 > 1 + rand 10
SyntaxError: (irb):16: syntax error, unexpected tINTEGER, expecting keyword_do or '{' or '('
 from /Users/peter/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'


1 + rand is a valid statement on its own, and is therefore parsed as one. The 10 seems out of place to the parser, since you just gave it a full expression already. It wants an operator or something to extend the statement, not another term.

I'm not feeling very articulate right now, but I think that makes sense. Right?


For what it's worth, you can do

1.+ rand 10
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜