2014-02-19 89 views
2

假设我拥有IP地址10.0.0.47
我该如何巧妙操纵它以便让我留下10.0.0.
chop想起来,但它不够动态。无论最后的.后面的数字是由1或3位数字组成,我都希望它工作。选择IP的一部分

回答

4

使用String#rindexString#[]与范围:

ip = "10.0.0.47" 
ip[0..ip.rindex('.')] # from the first character to the last dot. 
# => "10.0.0." 

或使用正则表达式:

ip[/.*\./]  # greedy match until the last dot 
# => "10.0.0." 

,或者使用String#rpartitionArray#join

ip.rpartition('.')[0,2].join 
# => "10.0.0." 
+0

'rindex'是一个有趣的发现,太棒了! – krystah

+0

@krystah,我刚加了另一个选择('rpartition' +'join') – falsetru

3
str[/(\d+\.){3}/] 
# => "10.0.0." 
+0

正确使用String#[]'.. +1 –