2014-02-19 94 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 –