You don't want that. What you're asking for is a side-effect, it's a function that does something other than return values and modify its own object and parameters. Worse, it directly affects the caller. Side-effects are the bane of maintainable code. They break encapsulation and make you have to carefully study every function call and consider its side-effects.
This is better solved by returning values and assigning this to variables. Ruby even supports returning multiple values, so you can return it as two values, not an Array of two values.
def create_variables_here
xyz=5
zyx=6
return xyz, zyx
end
def some_method
xyz, zyx = create_variables_here
puts xyz
puts zyx
end
You don't see this much because return values are usually related, and if they're related they should probably be returned as a single object. If they're not related, this might be a good indication that function is doing too many things.
That does everything you wanted, and it lets the caller decide what the variables are called. That's important, because it A) is one less thing for the caller to remember, B) it avoids conflicting with variables in the function, and C) makes it obvious where those variables came from.
As a counter example, let's say you had this.
def some_method
do_this
do_that
do_some_other_thing
puts xyz
puts zyx
end
...where did xyz
and zyx
come from?! Normally the answer would be simple: they're uninitialized. But with your proposed feature, the reader now has to carefully examine each do_blah
function call for side-effects that might have set xyz
and zyx
.
(You might say, "but any function that uses a side effect variable should have a name like create_vars_for_blah
." Yes, they should, but you can't count on that. It's better to not have the dangerous feature in the first place than to trust everyone will use it with care.)
Worse, what if they all set xyz
and zyx
to different values? Now you have a conflict. The caller has to find this conflict, and do something convoluted like:
def some_method
do_this
this_xyz = xyz
this_zyx = zyx
do_that
that_xyz = xyz
that_zyx = zyx
do_some_other_thing
some_other_xyz = xyz
some_other_zyx = zyx
...
end
Another problem with the idea is breaking local variables. One of the most important aspects of a local variable is you can, at a glance, see all the code that can affect it. For example.
def some_method
xyz = 10
zyx = 20
do_this
do_that
do_some_other_thing
puts xyz
puts zyx
end
In normal Ruby, we know for a fact that will print 10 and 20. With this proposed feature, who knows what they'll be?
What you're asking for is global variables that disappear at the end of the function.