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

kuqin91 · January 09, 2023 · Last by xinyifly replied at January 10, 2023 · 488 hits
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.

Reply to piecehealth

感谢大佬👍 👍

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

Reply to yetrun

ruby 3.2 a[5,1]就是nil

Reply to 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]
=> ""
You need to Sign in before reply, if you don't have an account, please Sign up first.