Ruby 新人刚学 Ruby,请教下各位大神字符串取值的问题

kuqin91 · 2023年01月09日 · 最后由 xinyifly 回复于 2023年01月10日 · 483 次阅读
a = "hello"
puts a[4,1]    # => o
puts a[5,1]    # => ""
puts a[6,1]    # => nil 

请问大佬们为啥 a[5,1] 是 "" 呢?

https://rubyapi.org/2.7/o/string#method-i-5B-5D

Additionally, an empty string is returned when the starting index for a character range is at the end of the string.

piecehealth 回复

感谢大佬👍 👍

牛皮啊,才知道还可以这么用

yetrun 回复

ruby 3.2 a[5,1]就是nil

piecehealth 回复
➜  ~ ruby --version
ruby 3.2.0 (2022-12-25 revision a528908271) [x86_64-linux]
➜  ~ irb
irb(main):001:0> a = "hello"
=> "hello"
irb(main):002:0> a[5,1]
=> ""
需要 登录 后方可回复, 如果你还没有账号请 注册新账号