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

ending = string[-n..-1]

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

What workarounds are available?

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

For ruby 1.9+

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

For ruby 2.0+, join returns a string

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

Ruby相关问答推荐

有没有更好的方法来加入剩余不变的子列表?

使用 Ruby,是否可以将 BigDecimal("1") / BigDecimal("3") 打印为 0.3333333333333... 到任意长度?

在 MacOS Sierra 上使用 RMagick 2.16 的 ImageMagick 7 找不到 MagickWand.h

Ruby 的 Object#taint 和 Object#trust 方法是什么?

如何判断 Ruby 数组是否包含多个值之一?

Ruby数组中的`return`#map

osx bash上的树命令

差异 - unless/if

Rails:Date.today 是 UTC 吗?

Ruby 是否有任何数字格式化类?

你喜欢哪种风格的 Ruby 字符串引用?

如何获取从位置 N 到 Ruby 中最后一个字符的子字符串?

将哈希转换为 struct

Ruby 的所有/最佳列表?

如何获取当前 rake 任务的 PID?

从数组 Ruby 中删除元素

未加载库:/opt/local/lib/libssl.1.0.0.dylib (LoadError)

检索/列出 Redis 数据库中的所有键/值对

如何在 Ruby 中创建整数循环?

Rubocop 25 线块大小和 RSpec 测试