Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Ruby function act like an explicit 'return' statement? [closed]

Tags:

ruby

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.

like image 728
Oeste Avatar asked Dec 25 '22 05:12

Oeste


1 Answers

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
like image 196
Alex P Avatar answered May 23 '23 05:05

Alex P