Rails: 将最后 n 个 IPv4 地址转换为通配符
Rails: Convert last n quartet's of IPv4 address to wildcard
我希望能够做到
irb(main):054:0> ip = "192.168.1.255"
=> "192.168.1.255"
irb(main):055:0> ip.sub(/\d+$/, '*')
=> "192.168.1.*"
最后 n 个四重奏。例如"192.168.1.255" => "192.168.*.*"
等
def wildcard ip, blocks=1
ip.split(".")[0..3-blocks].join(".") + ".*" * blocks
end
现已测试
[46] pry(main)> wildcard a
=> "192.168.0.*"
[47] pry(main)> wildcard a, 2
=> "192.168.*.*"
[48] pry(main)> wildcard a, 3
=> "192.*.*.*"
或者去 OOP
class String
def wildcard blocks=1
self.split(".")[0..3-blocks].join(".") + ".*" * blocks
end
end
# "192.168.0.1".wildcard => 192.168.0.*
# "192.168.0.1".wildcard(2) => 192.168.*.*
# "192.168.0.1".wildcard(3) => 192.*.*.*
您可以拆分“.”上的ip。并获得一系列四重奏。
def wildcard_ip(ip, n)
len = ip.split('.').size
ip.split('.').each_with_index.map{|q,i| i < len-n ? q : '*'}.join('.')
end
我希望能够做到
irb(main):054:0> ip = "192.168.1.255"
=> "192.168.1.255"
irb(main):055:0> ip.sub(/\d+$/, '*')
=> "192.168.1.*"
最后 n 个四重奏。例如"192.168.1.255" => "192.168.*.*"
等
def wildcard ip, blocks=1
ip.split(".")[0..3-blocks].join(".") + ".*" * blocks
end
现已测试
[46] pry(main)> wildcard a
=> "192.168.0.*"
[47] pry(main)> wildcard a, 2
=> "192.168.*.*"
[48] pry(main)> wildcard a, 3
=> "192.*.*.*"
或者去 OOP
class String
def wildcard blocks=1
self.split(".")[0..3-blocks].join(".") + ".*" * blocks
end
end
# "192.168.0.1".wildcard => 192.168.0.*
# "192.168.0.1".wildcard(2) => 192.168.*.*
# "192.168.0.1".wildcard(3) => 192.*.*.*
您可以拆分“.”上的ip。并获得一系列四重奏。
def wildcard_ip(ip, n)
len = ip.split('.').size
ip.split('.').each_with_index.map{|q,i| i < len-n ? q : '*'}.join('.')
end