arrays - 用于返回电子邮件数组的 Ruby 类方法

标签 arrays ruby class

我创建了一个包含类方法 find_by_emailUser 类:

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/

相关文章:

arrays - 如何在scala中合并一系列数组

c - 在循环中动态分配结构内存 t 次而不是声明结构数组

arrays - 用VBA编写求二维数组最小值的函数

ASP.NET 传递错误消息

netbeans 中的 javascript 类

c++ - 运算符(operator)在创建此2D节点阵列时是否遇到问题?

ruby - 为什么我需要 'active_support/core_ext' ?

ruby - 如何避免 Nilclass 的未定义方法错误

ruby csv 错误 : invalid byte sequence in UTF-8

javascript - JavaScript 对象中的私有(private)变量定义