Rails:将最后n个四重奏的IPv4地址转换为通配符

时间:2015-09-08 14:40:15

标签: ruby-on-rails regex gsub ipv4

我希望能够做到

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.*.*"等。

2 个答案:

答案 0 :(得分:1)

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.*.*.*

答案 1 :(得分:1)

您可以在“。”上拆分ip。得到一系列四重奏。

def wildcard_ip(ip, n)
  len = ip.split('.').size
  ip.split('.').each_with_index.map{|q,i| i < len-n ? q : '*'}.join('.')
end