【问题标题】:check if a variable is in array in ruby检查变量是否在ruby的数组中
【发布时间】:2015-02-21 20:22:03
【问题描述】:

我的所有 IP 都在一个数组中,如下所示。

list_of_ips = Socket.ip_address_list.select{|intf| intf.ipv4?}

我正在尝试使用 Enumerable include 来检查此数组是否包含它所包含的 IP 192.168.1.27,但我得到的返回值为 false。

puts list_of_ips[1].ip_address  ## This prints 192.168.1.27
puts $this_is_my_ip             ## This prints 192.168.1.27

puts list_of_ips.include? '192.168.1.27'  ## Gives me false

我想我需要用 ip_address 以某种方式过滤数组,但不确定如何。

【问题讨论】:

    标签: ruby arrays enumerable


    【解决方案1】:

    您需要将数组中的对象临时转换为字符串,以便将它们与字符串进行比较。试试这个:

    list_of_ips.map {|addr| addr.ip_address}.include? '192.168.1.27'
    

    【讨论】:

    • 是的..它是......投票赞成。
    • list_of_ips.map(&:ip_address)
    • @max:我总是忘记那个捷径,尽管我已经使用 ruby​​ 多年了。谢谢!
    【解决方案2】:
    list_of_ips.any? {|ip| ip.ip_address == '192.168.1.27'}
    

    【讨论】:

    • 聪明...还有什么吗? :)
    猜你喜欢
    • 1970-01-01
    • 2011-12-06
    • 2011-02-26
    • 2023-04-09
    • 1970-01-01
    • 2022-11-17
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多