Ruby:在字符处拆分字符串,从右侧开始计数 [英] Ruby: Split string at character, counting from the right side

查看:46
本文介绍了Ruby:在字符处拆分字符串,从右侧开始计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短版本——如何在 ruby​​ 中执行 Python rsplit()?

Short version -- How do I do Python rsplit() in ruby?

更长的版本 -- 如果我想在第一个 '.' 处将字符串分成两部分(名称、后缀)性格,这很好地完成了工作:

Longer version -- If I want to split a string into two parts (name, suffix) at the first '.' character, this does the job nicely:

name, suffix = name.split('.', 2)

但是如果我想在最后(最右边)分割'.'性格,我想不出比这更优雅的东西了:

But if I want to split at the last (rightmost) '.' character, I haven't been able to come up with anything more elegant than this:

idx = name.rindex('.')
name, suffix = name[0..idx-1], name[idx+1..-1] if idx

注意原来的名字字符串可能根本没有点,在这种情况下名字应该保持不变,后缀应该为零;它也可能有多个点,在这种情况下,只有最后一个点之后的位才是后缀.

Note that the original name string may not have a dot at all, in which case name should be untouched and suffix should be nil; it may also have more than one dot, in which case only the bit after the final one should be the suffix.

推荐答案

String#rpartition 就是这样做的:

String#rpartition does just that:

name, match, suffix = name.rpartition('.')

它是在 Ruby 1.8.7 中引入的,因此如果运行早期版本,您可以使用 require 'backports/1.8.7/string/rpartition' 使其工作.

It was introduced in Ruby 1.8.7, so if running an earlier version you can use require 'backports/1.8.7/string/rpartition' for that to work.

这篇关于Ruby:在字符处拆分字符串,从右侧开始计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆