Orsay Orsay - 4 months ago 19
Ruby Question

How to make boolean as method result?

I create a method which is supposed to send me a boolean.
But within it there is a loop who send also boolean.
Sometimes the loop send true sometimes false and I would like my method to send true as soon there is one true.

def update_with_former_email?(update_email)
self.versions.each do |version|
next if version.object.nil?
version.object.include?(update_email)
end
end


For the moment when I call my method like:

person.update_with_former_email?("orsay@gmail.com")


it sends me the whole object
self.versions

Answer

each returns the object it was called upon, i.e. self. To return an actual boolean value derived from include?, you can use return:

def update_with_former_email?(update_email)
  self.versions.each do |version|
    next if version.object.nil?
    return true if version.object.include?(update_email)
  end

  return false
end

or better use any? instead of each:

def update_with_former_email?(update_email)
  self.versions.any? do |version|
     version.object.present? && version.object.include?(update_email)
  end
end
Comments