如何在Ruby中从开头索引到最终选择字符串的一部分?

use*_*444 2 ruby

string = "Yellow"
puts string[1..string.length] -> outputs "ellow"
Run Code Online (Sandbox Code Playgroud)

有没有一种更短的方法让Ruby在不使用string.length的情况下做同样的事情?例如,在Python中,我们可以编写字符串[1:]并执行它.

提前致谢.

Cha*_*ell 8

[]在Ruby中使用获取String或Array的索引时,使用负数将从索引的末尾开始计数1([-0]将使您与之相同[0]).

在你的例子中,

puts string[1..-1] 
Run Code Online (Sandbox Code Playgroud)

将输出所需的字符串"ellow".相等,

puts string[1..-2] 
Run Code Online (Sandbox Code Playgroud)

会产生"ello"等等.

字符串#[]的文档