【问题标题】:How to scan and remove elements from an array and return the array? [closed]如何扫描和删除数组中的元素并返回数组? [关闭]
【发布时间】:2014-01-20 18:02:19
【问题描述】:

我正在尝试扫描一组电子邮件地址并从该数组中删除特定的域地址,然后将其返回。

这是我的代码:

matches = ["abuse@peterstar.net", "hostmaster@peterstar.net", "noc@peterstar.net", "noc@tristatevoicedata.com", "abuse@ripe.net", "dpereira@affiliatedtech.com"]
email = Array.new()
emails = Array.new()
matches.each do |email|
  if email != 'nobody@peterstar.com' && !email.match('@peterstar.net') && !email.match('@ripe.net') && !email.match('@arin.net') && !email.match('@lacnic.net') && !email.match('@afrinic.net')
    emails = email
    puts emails
  end
end
puts emails

这是脚本的输出:

dpereira@affiliatedtech.com

我需要知道如何返回一个删除了给定元素的数组。上面的脚本只返回数组的最后一个元素作为字符串。

提前致谢。

【问题讨论】:

标签: ruby arrays


【解决方案1】:

Regexp:

re = /(^nobody@peterstar.com|@peterstar.net|@ripe.net|@arin.net|@lacnic.net|@afrinic.net)/
matches.select {| email | email !~ re }
# => ["noc@tristatevoicedata.com", "dpereira@affiliatedtech.com"]

带有电子邮件数组和电子邮件模板:

res = [
  'nobody@peterstar.com',
  /@peterstar.net/,
  /@ripe.net/,
  /@arin.net/,
  /@lacnic.net/,
  /@afrinic.net/, ]
emails = matches.reject {| email | res.any? {| re | re === email } }
# => ["noc@tristatevoicedata.com", "dpereira@affiliatedtech.com"]
emails.last
# => "dpereira@affiliatedtech.com"

或者使用卷积或归约:

res = [
  'nobody@peterstar.com',
  /@peterstar.net/,
  /@ripe.net/,
  /@arin.net/,
  /@lacnic.net/,
  /@afrinic.net/, ]
  matches.reduce(nil) {| email, match | !res.any? {| re | re === match } && match || email }
  # => "dpereira@affiliatedtech.com"

也请参考rubydocumentation on Arrays,远离PHP的思维方式。

【讨论】:

  • 谢谢,但我无法访问循环外的电子邮件变量:(
  • @user3155632 在您的上下文中是什么意思?要访问循环外的变量,您需要在循环之前声明它。
  • 是的,我当然喜欢email = "",甚至尝试过email = nil
  • 它只是给出true而不是输出值
  • 我完全理解不是你的意思吗?
【解决方案2】:

这种模式:

/(?:@(?:a(?:frinic|rin)|peterstar|lacnic|ripe)\.net|nobody@peterstar\.com)/i

与您的列表匹配:

if email != 'nobody@peterstar.com' && !email.match('@peterstar.net') && !email.match('@ripe.net') && !email.match('@arin.net') && !email.match('@lacnic.net') && !email.match('@afrinic.net')

这是Rubular displays it的方法。

下面是如何使用它:

MATCHES = %w[
  abuse@peterstar.net
  hostmaster@peterstar.net
  noc@peterstar.net
  noc@tristatevoicedata.com
  abuse@ripe.net
  dpereira@affiliatedtech.com
]
REGEX = /(?:@(?:a(?:frinic|rin)|peterstar|lacnic|ripe)\.net|nobody@peterstar\.com)/i

如果你想要匹配的字符串:

MATCHES.reject{ |s| s[REGEX] }
# => ["noc@tristatevoicedata.com", "dpereira@affiliatedtech.com"]

如果你想要 DO 匹配的字符串:

MATCHES.select{ |s| s[REGEX] }
# => ["abuse@peterstar.net",
#     "hostmaster@peterstar.net",
#     "noc@peterstar.net",
#     "abuse@ripe.net"]

该模式使用i 标志来强制不区分大小写,这在处理电子邮件地址时很重要,因为它们不区分大小写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2016-10-31
    相关资源
    最近更新 更多