2016-01-27 63 views

回答

5

可以做到这样:

ip = "208.68.38.12" 
ip.split(".")[0...-1].join(".") 
#=> "208.68.38" 

如果你一步一步来,上面的代码使用的线是相当不言自明的。在这里:

ip.split(".") # splitting string on `.` so we have an Array 
#=> ["208", "68", "38", "12"] 
ip.split(".")[0...-1] # taking 0th to n-1 th element of Array (-1 represents last element when size is unknown) 
#=> ["208", "68", "38"] 
ip.split(".")[0...-1].join(".") # finally joining the Array over `.` 
#=> "208.68.38" 
1

尝试:

"208.68.38.12".split('.')[0,3].join('.') #=> "208.68.38" 
0

假设你可以依靠一个结构完整的IPv4地址:

ip.sub(/\.[^.]*\z/, '') 
0
ip = ip.split('.')[0..-2].join('.') 
1
ip = '208.68.38.12' 
ip[/.*(?=\.\d+\z)/] 
#⇒ "208.68.38" 

这里我们使用String#[]和积极前瞻在正则表达式中省略最后一个点和后面的数字吨。

顺便说一句,有各种各样的处理IP的宝石,摹:https://github.com/deploy2/ruby-ip

2

另一个版本:

ip = "208.68.38.12" 
ip[0...ip.rindex('.')] # => "208.68.38" 
0

简单的方式,在我看来:

"208.68.38.12"[/(\.?\d+){3}/]