开发者

Syntax error, expecting "="

开发者 https://www.devze.com 2023-01-06 21:40 出处:网络
I\'m trying to write a Rubyish solution to problem 6 in Project Euler, because I have the propensity to write C in other languages. However, this code:

I'm trying to write a Rubyish solution to problem 6 in Project Euler, because I have the propensity to write C in other languages. However, this code:

sqrsum, sumsqr = 0, 0
(1..100).each { |x| sqrsum, sumsqr += x, x**2 }
p (sumsqr - (sqrsum ** 2))

kicks up these errors:

/Users/Andy/Documents/Programming/Ruby/ProjectEuler/P开发者_如何学Go6.rb:2: syntax error, unexpected tOP_ASGN, expecting '='
(1..100).each { |x| sqrsum, sumsqr += x, x**2 }
                                     ^
/Users/Andy/Documents/Programming/Ruby/ProjectEuler/P6.rb:2: syntax error, unexpected tPOW, expecting '='
(1..100).each { |x| sqrsum, sumsqr += x, x**2 }
                                            ^

What am I doing wrong here? Am I only allowed to assign in that syntactic structure?


You are trying to make multiple assignments, but you are not using the assignment operator =. Compare sqrsum, sumsqr = 0, 0 with sqrsum, sumsqr += x, x**2.

Probably you wanted to write sqrsum, sumsqr = sqrsum+x, sumsqr+x**2.


why not just do { |x| sqrsum += x; sumsqr += x**2}


you could also use inject

sqrsum, sumsqr = (1..100).inject(:+), (1..100).inject(0) { |result,x| result + x**2 }
p(sumsqr - sqrsum**2)

[edit: thanks to commenters for pointing out :+ shorthand]


Do you want that

sqrsum, sumsqr = sumsqr + x, x**2

0

精彩评论

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

关注公众号