【问题标题】:Compare arrays in Ruby比较 Ruby 中的数组
【发布时间】:2016-05-13 03:49:51
【问题描述】:

我有一组完全限定的域名:

["filer1.abc.com", filer2.abc.com, filer3.xyz.com]

我有另一个包含主机名的数组:

["filer1", "filer3"]

我必须比较两个数组,如果主机名存在于 fqdn 中,那么我需要从第一个数组中获取 fqdn。例如,"filer1" 存在于"filer1.abc.com" 中,所以我需要获取值"filer1.abc.com"。而"filer3" 存在于"filer3.xyz.com" 中,所以我需要获取"filer3.xyz.com" 的值。

感谢您的帮助。

["filer1.abc.com", filer2.abc.com, filer3.xyz.com].map.each_with_index {|vserver, indx| vserver.id.include? host_names[indx] unless host_names[indx].nil?}}

我得到[true, nil, nil, nil],但实际上我需要像["filer1.abc.com"] 这样的fqdn 值。

【问题讨论】:

  • 选择代替地图听起来像您正在寻找的东西
  • filer2filer3 是什么? abcxyzcom这些方法有什么作用?
  • sawanese 的翻译:如果“filer2.abc.com”和“filer3.xyz.com”是字符串,它们需要用引号括起来。

标签: arrays ruby dictionary enumerator


【解决方案1】:
fqdn_array = ["filer1.abc.com", "filer2.abc.com", "filer3.xyz.com"]
hostnames = ["filer1", "filer3"]

result = fqdn_array.keep_if{|fqdn| (hostnames - fqdn.split('.')).length < hostnames.length}
# => ["filer1.abc.com", "filer3.xyz.com"] 

Array#keep_if 遍历数组并保留块为真的所有元素。在块中,我将点处的 fqdn 拆分为一个数组。然后我从主机名数组中减去它。如果结果比原始数组长度短,我找到了一个 fqdn,其中包含您的一个主机名,并且条件返回 true。

【讨论】:

  • 我认为使用include? 会使事情更具可读性fqdn_array.keep_if{|fqdn| hostnames.include? fqdn.split('.')[0] }
  • 不客气。如果这是适合您的解决方案,请接受此答案。
  • @thomas-haratyk:如果有像“abc.filer1.com”这样的 fqdn,我的解决方案也可以。
猜你喜欢
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
相关资源
最近更新 更多