Conditionally exiting the current method?

J

Jason Burgett

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]?
 
F

Fabian Streitel

[Note: parts of this message were removed to make it a legal post.]

just call return.

Greetz!
 
R

Ryan Davis

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]?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,979
Messages
2,570,185
Members
46,722
Latest member
NelsonHeil

Latest Threads

Top