Brent Eicher
Brent Eicher

Reputation: 1050

Return false to invoking method

I have the following class and want the steps to return false when it arrives at step_two:

class Something

  def steps
    step_one
    step_two
    step_three
  end

  private

    def step_one
      some_function
    end

    def step_two
      if some_other_function
        return false
      end
      true
    end

    def step_three
      some_function
    end

end

As this is written, the steps method will not stop execution at step_two and will proceed to step_three. I can write it in this way to make it work:

def steps
  step_one
  return false unless step_two
  step_three
end

Or if all three steps could return false:

def steps
  return false unless step_one
  return false unless step_two
  return false unless step_three
end

Is there a better way to do this? I guess I'm asking if an invoking method in Ruby can return false if an invoked method returns false?

Upvotes: 0

Views: 246

Answers (3)

Paul Richter
Paul Richter

Reputation: 11072

Since your method step_two is returning false, the issue is because your if statement is resolving to false, and happily proceeds to step_three. You have a couple of options:

Use the unless operator instead of if, like so:

def steps
  step_one
  return false unless step_two
  step_three
end

or you can use the ! (not) operator:

def steps
  step_one
  return false if !step_two
  step_three
end

Update

From the clarification in the comments, you want your step method to return false if any of the other method calls return false, or true if everything returned true. Practically speaking, something like this:

def steps
  step_one && step_two && step_three
end

In this case, if any of the methods return false, because we are using && (and) operators, the whole thing fails, and you receive a false value. For example, if step_one returns true, and step_two returns false, step_three is never run and the value of the whole operation is resolved to false.

Upvotes: 1

hdk
hdk

Reputation: 11

What about?

def steps
  step_one
  if step_two
      step_three
  end
end

Is this better to you?

Upvotes: 0

kroky
kroky

Reputation: 1316

You can chain method invocation and conditionally execute further steps only if previous return true like this:

def steps
  step_one and step_two and step_three
end

This way, steps method will also return true or false based on the overall execution of each step - i.e. true will mean all steps were executed successfully.

Upvotes: 2

Related Questions