从 ruby​​ 字符串中提取最后 n 个字符 [英] Extracting the last n characters from a ruby string

查看:64
本文介绍了从 ruby​​ 字符串中提取最后 n 个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要从字符串中获取最后一个 n 字符,我假设您可以使用

To get the last n characters from a string, I assumed you could use

ending = string[-n..-1]

但是如果字符串的长度小于 n 个字母,你会得到 nil.

but if the string is less than n letters long, you get nil.

有哪些可用的解决方法?

What workarounds are available?

背景:字符串是纯 ASCII,我可以访问 ruby​​ 1.9.1,我使用的是普通的旧 Ruby 对象(没有网络框架).

Background: The strings are plain ASCII, and I have access to ruby 1.9.1, and I'm using Plain Old Ruby Objects (no web frameworks).

推荐答案

这里有一个单行,可以放一个大于字符串大小的数字:

Here you have a one liner, you can put a number greater than the size of the string:

"123".split(//).last(5).to_s

对于 ruby​​ 1.9+

For ruby 1.9+

"123".split(//).last(5).join("").to_s

对于 ruby​​ 2.0+,join 返回一个字符串

For ruby 2.0+, join returns a string

"123".split(//).last(5).join

这篇关于从 ruby​​ 字符串中提取最后 n 个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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