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

标签 ruby

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

相关文章:

ruby - Highgui 和 ruby

css - 如何自定义 rdoc Darkfish 样式表?

ruby-on-rails - 通过 Gmail 发送电子邮件但配置不同的电子邮件地址

ruby-on-rails - ActiveRecord::Base中的::Base部分含义

ruby - 获取创建另一个实例的实例

javascript - 为什么我的 Rails AJAX 删除方法只有在我刷新时才有效?

ruby - 获取数组中三个连续元素的值

ruby - 我如何编写 "if a process is running for longer than n seconds, kill it"的 Resque 条件?

ruby-on-rails - CollectionProxy 与 AssociationRelation

ruby-on-rails - ActiveRecord::Base.store 自动类型转换