Tintin81
Tintin81

Reputation: 10207

How best to loop through multiple functions in Ruby?

Is there a more concise way to loop through a number of conditions than this?

def is_this_whole_thing_true?
  result = false
  result = true if condition_1?
  result = true if condition_2?
  result = true if condition_3?
  result = true if condition_4?
  result = true if condition_5?
  result = true if condition_6?
  result = true if condition_7?
  result
end

Thanks for any help.

Upvotes: 1

Views: 38

Answers (2)

Ursus
Ursus

Reputation: 30056

If you don't care to create a whole array I think this is the best option

def is_this_whole_thing_true?
  conditions = [condition1?, condition2?, condition3?, condition4?]
  conditions.any?
end

Upvotes: 5

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

you can simply put && condition here like:

def is_this_whole_thing_true?
  condition_1? && condition_2? && condition_3? && ...
end

Infact, what you are trying to do in the method is return true if any of the condition is true, then use ||

def is_this_whole_thing_true?
  condition_1? || condition_2? || condition_3? || ...
end

An advantage of this is, it won't check all of the conditions, as soon as any one of the condition turns out to be true, it will return.

Upvotes: 1

Related Questions