Conditionally exiting the current method?

I’m trying to exit a running method after a certain condition is met. I
have a master method executing sever methods within the same class.

Example:

def self.method_1(user)
words = ["hello", "goodbye", "bonjour"]
user.strings.each do |string|
    words.each do |word|
      if string.text.downcase.include? word.downcase
        puts "I found #{word}"
      end
    end
  end

end

def self.method_2
    put "This is method 2"
end

In the above example, how do I stop execution on [method_1] after [puts
“I found #{word}”] so it can continue on to [method_2]?

On Jul 12, 2009, at 22:28 , Jason B. wrote:

reformatted for readability:

def self.method_2
put “This is method 2”
end

In the above example, how do I stop execution on [method_1] after
[puts
“I found #{word}”] so it can continue on to [method_2]?

First off, don’t use #each when you don’t need to. Look at the methods
available in Enumerable. There is a lot of candy and magic there.
Further, words is an array, and all the contents are already
downcased, so you’re doing a lot of extra work where you don’t need
to. Check it:

def self.method_1(user)
words = %w(hello goodbye bonjour)
word = user.strings.find { |string|
words.find { |word| string.text.downcase.include? word }
}
puts “I found #{word}” if word
end

Since words is an array of words and you’re just looking for a match
of one of those words inside the user strings, use a regexp:

def self.method_1 user
words = Regexp.union %w(hello goodbye bonjour)
word = user.strings.any? { |string| string.text =~ words }
puts “I found #{word}” if word
end

Depending on how user.strings is composed, it might be cleaner and
faster to use grep:

def self.method_1 user
words = user.strings.grep Regexp.union(%w(hello goodbye bonjour))
puts “I found #{words.first}” unless words.empty?
end

You may have to do some massaging to get it to work with whatever type
of object user.strings returns, but the idea is the same.

just call return.

Greetz!