Ruby:如何将IP范围转换为IP数组

Kit*_* Ho 4 ruby ip

有没有简单的方法将IP范围转换为IP数组?

def convertIPrange (start_ip, end_ip)
 #output: array of ips end
end
Run Code Online (Sandbox Code Playgroud)

例如输入

('192.168.1.105', '192.168.1.108') 
Run Code Online (Sandbox Code Playgroud)

产量

['192.168.1.105','192.158.1.106','192.158.1.107','192.158.1.108']
Run Code Online (Sandbox Code Playgroud)

Bea*_*rtz 10

使用Ruby标准库 IPAddr

# I would suggest naming your function using underscore rather than camelcase
# because of Ruby naming conventions
#
require 'ipaddr'

def convert_ip_range(start_ip, end_ip)
  start_ip = IPAddr.new(start_ip)
  end_ip   = IPAddr.new(end_ip)

  # map to_s if you like, you can also call to_a, 
  # IPAddrs have some neat functions regarding IPs, 
  # be sure to check them out
  #
  (start_ip..end_ip).map(&:to_s) 
end
Run Code Online (Sandbox Code Playgroud)