Understanding "Useless assignment to variable"

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).

Upvotes: 3

Views: 15907

Answers (2)

IIsi 50MHz
IIsi 50MHz

Reputation: 78

You can explicitly return a value to suppress that error. Like so:

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

You can also shorten it a bit:

def get_sum(num1, num2)
   return num1 + num2
end
puts get_sum(1, 1)

And as you seem to have discovered, you can leave out the keyword 'return' if all you care about is the result of the last expression.

See: Howtogeek Ruby Function (method) Syntax

Upvotes: 0

coreyward
coreyward

Reputation: 80041

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.

Upvotes: 8

Related Questions