Question

Lets say you have a method that assigns a variable to a method call at the end:

def this_method(x)
   x = x + 5
   x = some_method_like_multiply_by_two(x)
end

and a similar method that doesn't have a variable assignment:

def this_method(x)
   x = x + 5
   some_method_like_multiply_by_two(x)
end

Which one is better? Is it necessary to have x = in the last statement of a method? Is the first one clearer? Does the second one pose a risk to introduce more bugs by whoever read the code because they might not know that its doing something with x? Which one is the proper way of coding? When would I want to use the first style (despite the variable is showing as unused in code analysis)?

Was it helpful?

Solution

Why not simplify life even further and do:

def this_method(x)
   some_method_like_multiply_by_two(x + 5)
end

Since x is purely local to the method and you are returning the result of calling the other method, updating x with intermediate operations accomplishes nothing. Go straight for the goal.

OTHER TIPS

Are you trying to change the value of "x" as passed into this_method? If not then "x =" is wasted effort, especially because you are not using x, unless you are returning x from the method. If you are you have two options:

def this_method(x)
   x = x + 5
   x = some_method_like_multiply_by_two(x)
   return x
end

or just simply:

def this_method(x)
   x = x + 5
   x = some_method_like_multiply_by_two(x)
   x
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top