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/P6.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, 0withsqrsum, sumsqr += x, x**2.Probably you wanted to write
sqrsum, sumsqr = sqrsum+x, sumsqr+x**2.