tags:

views:

86

answers:

2

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/peter/.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>'
+4  A: 

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?

Matchu
Does this mean that arithmetic has higher precedence than function application? Most other languages are the other way around, AFAIK.
Marcelo Cantos
I'm not sure of the actual precedence chain, but I'm betting that `unambiguous(form)` has higher precedence than the `ambiguous form`.
Matchu
1 + rand(10) => 9 #-# 1 + (rand 10) => 3 #-# Looks like the explicitly parenthesis have higher precedence than the + but not the implicit parens of a blank rand 10 call
Paul Rubel
is there such thing as precedence of implicite paren vs explicit paren? doesn't seem to have such thing in the table of the Programming Ruby book? Is the paren even an operator?
動靜能量
there might be better answers... but right now this seems to be the best answer, that 1 + rand is taken as a unit, and adding a 10 after it doesn't make sense as a result
動靜能量
+1  A: 

For what it's worth, you can do

1.+ rand 10
Andrew Grimm