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

Carlos Rojas

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.

bashaus

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" 

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Why switch case in javascript doesn't work with string on Microsoft Edge?

분류에서Dev

Why isEOF doesn't work?

분류에서Dev

Why json doesn´t work?

분류에서Dev

Why doesn't isdigit() work?

분류에서Dev

Why getDeclaredMethod doesn't work with arguments which are in relation instanceof with specific method?

분류에서Dev

The addEventListener method doesn't work in JavaScript File

분류에서Dev

SqlDataAdapter.FillSchema() method doesn't work

분류에서Dev

SetValue method doesn't work after DoubleAnimation

분류에서Dev

Why doesn't LibreOffice work with the HUD?

분류에서Dev

Why wmctrl doesn't work for certain windows?

분류에서Dev

Why doesn't this math work with macros?

분류에서Dev

Why doesn't beep work in Ubuntu?

분류에서Dev

Why doesn't my SetLength work?

분류에서Dev

why the click() function doesn't work?

분류에서Dev

Why doesn't this simple enable_if work?

분류에서Dev

Why doesn't this Mongoose query work?

분류에서Dev

Why doesn't my iptables rule work?

분류에서Dev

Why this jQuery doesn't work in Codeigniter?

분류에서Dev

Why doesn't source lib/* work?

분류에서Dev

Jquery Why doesn't toggleClass work here?

분류에서Dev

Why char[] work,but char * doesn't

분류에서Dev

why doesn't history work in Ubuntu?

분류에서Dev

Why doesn't this batch command work as expected?

분류에서Dev

Why doesn't "usermod" work under superuser?

분류에서Dev

Why doesn't my .desktop file work?

분류에서Dev

String comparison using in doesn't work with unless

분류에서Dev

String matching doesn't work as expected

분류에서Dev

Event doesn't work when element isn't loaded directly

분류에서Dev

Why doesn't this program echo any string?