【发布时间】:2012-02-16 15:25:49
【问题描述】:
脚本必须验证一个预定义的 IP 是否存在于一大堆 IP 中。目前我像这样编写函数(说“ips”是我的 IP 数组,“ip”是预定义的 ip)
ips.each do |existsip|
if ip == existsip
puts "ip exists"
return 1
end
end
puts "ip doesn't exist"
return nil
有没有更快的方法来做同样的事情?
编辑:我可能错误地表达了自己。我可以做array.include吗?但我想知道的是:是array.include吗?哪种方法能给我最快的结果?
【问题讨论】:
-
使用哈希或集合代替数组
-
在任何 Ruby 编程之前阅读ruby-doc.org/core-1.9.3/Enumerable.html。
-
你可以使用
Array类中定义的include?方法让这个操作看起来更整洁,我不确定它是否会大大提高查找速度 -
@JosephLeBrech 这里的问题是关于搜索数组。
标签: ruby arrays string loops comparison