为什么危险的方法对 Ruby 中的 String 字符元素不起作用?

Why a dangerous method doesn't work with a character element of String in Ruby?

当我应用 upcase! 方法时,我得到:

a="hello"
a.upcase!
a # Shows "HELLO"

但在另一种情况下:

b="hello"
b[0].upcase!
b[0]  # Shows h
b # Shows hello

我不明白为什么 upcase! 应用于 b[0] 没有任何效果。

b[0] returns 一个新的 String 每次。查看对象 ID:

b = 'hello'
# => "hello"
b[0].object_id
# => 1640520
b[0].object_id
# => 25290780
b[0].object_id
# => 24940620

当您选择字符串中的单个字符时,您并不是在引用特定字符,而是在调用执行评估的 accessor/mutator 函数:

2.0.0-p643 :001 > hello = "ruby"
 => "ruby" 
2.0.0-p643 :002 > hello[0] = "R"
 => "R" 
2.0.0-p643 :003 > hello
 => "Ruby" 

在你运行危险方法的情况下,访问者请求该值,然后对其进行操作并更新新变量,但是因为角色和字符串,它不会更新引用。

2.0.0-p643 :004 > hello = "ruby"
 => "ruby" 
2.0.0-p643 :005 > hello[0].upcase!
 => "R" 
2.0.0-p643 :006 > hello
 => "ruby"