我是 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/