Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding "Useless assignment to variable"

Tags:

ruby

I have a Ruby function that returns a single variable subsequently used by the caller however I get the following warning

warning: assigned but unused variable

I have put together a contrived example that will show this error with "ruby -cw"

def get_sum(num1, num2)
  sum = num1 + num2
end
puts get_sum(1, 1)

and if I check it with "ruby -cw" I get the above warning. However I am using the "sum" variable - just not in that function's scope. How can I avoid this warning? (and satisfy Rubocop too).

like image 296
Friedrich 'Fred' Clausen Avatar asked Jun 17 '26 22:06

Friedrich 'Fred' Clausen


1 Answers

You're not using the sum variable for anything. The following does the same thing:

def sum(a, b)
  a + b
end

Because sum is local to your get_sum method, it is not available outside of that context.

like image 108
coreyward Avatar answered Jun 21 '26 01:06

coreyward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!