gpt4 book ai didi

Ruby:当使用 []= 改变字符串的内容并且超出范围时

转载 作者:数据小太阳 更新时间:2023-10-29 08:05:55 24 4
gpt4 key购买 nike

我是 Ruby 的新手,正在阅读 "Ruby Programming Language" ,当遇到“3.2.4 访问字符和子字符串”部分时,在第 56 和 57 页上有一个示例说明使用 []= 更改字符串内容:

s = 'hello'; # Ruby 1.9
....
....
s[s.length] = ?! # ERROR! Can't assign beyond the end of the string

是的,这是真的,你不能在字符串末尾之外赋值。
但是,当我在 IRB 上使用它时,我得到了不同的结果:

irb(main):016:0> s[s.length] = ?!
=> "!"
irb(main):017:0> s
=> "hello!"

Ruby 1.9.2p180 (2011-02-18 revision 30909) on Mac OS X 10.6.8

最佳答案

这本书是 2008 年的,示例使用的是 Ruby 1.8,在 1.9.2 中完美运行:

# Ruby 1.8.7-p352
s = 'hello'
s[s.length] = ?!
puts s

# => IndexError: index 5 out of string
# method []= in ruby.rb at line 3
# at top level in ruby.rb at line 3

# Ruby 1.9.2-p290
s = 'hello'
s[s.length] = ?!
puts s

# => hello!

关于Ruby:当使用 []= 改变字符串的内容并且超出范围时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com