假设我有 IP 地址 10.0.0.47
我怎样才能巧妙地操纵它,以便我只剩下 10.0.0.
?
chop
突然想到,但它不够动态。无论最后一个 .
之后的数字是由 1 位还是 3 位数字组成,我都希望它能正常工作。
最佳答案
使用 String#rindex
和 String#[]
范围:
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#rpartition
和 Array#join
:
ip.rpartition('.')[0,2].join
# => "10.0.0."
关于ruby - 选择 IP 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21883823/