I'm trying to do something sort of unusual with a Ruby method. I'd like to make terminate act like an explicit return statement in the below code:
def terminate(data)
data.upcase
#I want to put a command somewhere in this scope
end
def other_method
data = "cow"
terminate data
data = "fox"
end
other_method
#Desired response
#> "COW"
#Actual response in everything that we try
#> "fox"
I want other_method to return "COW". Specifically, by causing 'terminate' to function as an explicit return statement. Is there something I can throw / raise that will do this? Or some other hacky way I can force this behavior?
Currently, in our code we always use (many, many instances of this across a large codebase, with frequent changes to it):
return foo! param1, param2
return foo2! param1, param2
return foo3! param1, param2
We'd like to replace this with:
foo! param1, param2
foo1! param1, param2
foo2! param1, param2
There is no other way foo! is used in our code base by design. It's basically syntactic sugar.
In Ruby, unless you use an explicit return
statement elsewhere in your method, the last line executed in your method is what's returned. Maybe the complexity is getting lost in your simpler example, but: can you store the result of terminate
in a variable and return that?
def other_method
data = "cow"
result = terminate data
data = "fox"
result
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With