ruby - 选择 IP 的一部分

标签 ruby string

假设我有 IP 地址 10.0.0.47
我怎样才能巧妙地操纵它,以便我只剩下 10.0.0.
chop 突然想到,但它不够动态。无论最后一个 . 之后的数字是由 1 位还是 3 位数字组成,我都希望它能正常工作。

最佳答案

使用 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."

关于ruby - 选择 IP 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21883823/

相关文章:

带有 i++++i 的 Ruby 括号语法异常

regex - Swift - 将属性字符串添加到括号中的项目

c - 在 C 中复制字符串数组时出错

Javascript\x 转义

ruby - 如何用 RSpec 测试这个?

ruby - Array#each 与 Array#map

c++ - 模板函数中 std::string 的类型推断失败

java - 是否可以将整数值字符串转换为 3 x 3 数组?

ruby - 错误 : failed to build gem native extension, Linux 虚拟机

ruby - 通过循环分配不同的变量名(它们是 nil 数组)