riversand15
riversand15

Reputation: 55

How can I refactor ruby code that calls different functions but does the same thing with their responses?

This is the method I was to refactor. What is a good way to refactor this code? Is there any way to put the method calls in a list and return as soon as one of the method returns a valid response?

  def method
    response_hash = method1
    return response_hash if response_hash.present?

    response_hash = method2
    return response_hash if response_hash.present?

    response_hash = method3
    return response_hash if response_hash.present?

    response_hash = method4
    return response_hash if response_hash.present?
  end

Upvotes: 1

Views: 49

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

Seems that you want to return the first non-empty result.

def my_method
  [:method1, :method2, :method3, :method4].each do |method_name|
    result = send(method_name)
    return result if result.present?
  end
end

Symbols / send are here to maintain the lazy nature of evaluations (don't evaluate more than necessary)

Upvotes: 3

Related Questions