我创建了一个包含类方法 find_by_email
的 User
类:
class User
attr_accessor :email
def initialize
@email="example@example.com"
end
def self.find_by_email(pattern)
ObjectSpace.each_object(self) do |object|
puts object.email+" "+(object.email.include? pattern).to_s
end
end
end
在 irb
我尝试:
irb> user1=User.new
irb> user2=User.new
irb> user1.email="sergio@example.com"
irb> User.find_by_email "s"
返回:
example@example.com false
sergio@example.com true
我希望find_by_email
返回一个包含匹配电子邮件的数组。所以对于这个例子,它应该只返回 ["sergio@example.com"]
。我如何重构 find_by_email
类来实现这一点?
最佳答案
您的方法不会返回,只会打印出它找到的内容。
你需要创建一个数组,添加到它,然后返回它。
def self.find_by_email(pattern)
# Create an empty array to store the emails.
emails = []
# Search!
ObjectSpace.each_object(self) do |object|
# If it matches, put the email in the array.
if object.email.include? pattern
emails << object.email
end
end
# Return the array.
emails
end
还有一点提醒。您可能应该远离 ObjectSpace
。这非常有助于您了解 ruby 应用程序,并进入您可能尚未准备好进入的某些领域。我会建议在使用它之前研究更多的 ruby 基础概念。即便如此,这也可能是个坏主意。
关于arrays - 用于返回电子邮件数组的 Ruby 类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57084633/