简体   繁体   中英

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

When I apply the upcase! method I get:

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

But in this other case:

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

I don't understand why the upcase! applied to b[0] doesn't have any efect.

b[0] returns a new String every time. Check out the object id:

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

When you are selecting an individual character in a string, you're not referencing the specific character, you're calling a accessor/mutator function which performs the evaluation:

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

In the case when you run a dangerous method, the value is requested by the accessor, then it's manipulated and the new variable is updated, but because there is no longer a connection between the character and the string, it will not update the reference.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM