.replace()
- 打开
irb
:
PS C:\Users\Administrator> irb --simple-prompt
- 创建字符串变量
str
,值为“hello”
,赋值给变量abc
,本质是使abc
指向同一个字符串对象,所以均输出为同一个“hello”
:
>> str = "Hello"
=> "Hello"
>> abc = str
=> "Hello"
- 对
str
变量使用.replace("")
,使其指向的object
的值修改为"Goodbye"
,直接导致指向同一个对象的abc
也会输出“Goodbye”
:
>> str.replace("Goodbye")
=> "Goodbye"
>> puts str
Goodbye
=> nil
>> puts abc
Goodbye
=> nil
.dup and .freeze
创建修改字符串方法change_string()
PS C:\Users\Administrator> irb --simple-prompt
>> def change_string(str)
>> str.replace("New String")
>> end
=> :change_string
example
- 被改变成新的字符串
>> s = "Hello world"
>> change_string(s)
>> puts s
New String
- .dup(duplicate)保持原来的值没有变化
>> s = "Hello world"
>> change_string(s.dup) # 对s使用.dup相当于创建了一个副本
>> puts s
Hello world
- can’t modify frozen String
>> s = "Good Day"
>> s.freeze
>> change_string(s)
RuntimeError: can't modify frozen String
freeze and replace
- 对
numbers
使用.freeze
,使得无法对numbers
进行修改操作 :
PS C:\Users\Administrator> irb
irb(main):001:0> numbers = ["one","two","three"]
=> ["one", "two", "three"]
irb(main):002:0> numbers.freeze
=> ["one", "two", "three"]
irb(main):005:0> numbers[2] = "four"
RuntimeError: can't modify frozen Array
from (irb):5
from C:/Ruby23-x64/bin/irb.cmd:19:in `<main>'
- 但是仍可以用.
replace
修改numbers
中的元素"three"
指向的对象的值 :
irb(main):006:0> numbers[2].replace("four")
irb(main):007:0> numbers
=> ["one", "two", "four"]
reference
《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
2.5. Local variables and variable assignment 2.5.1~2.5.3
∧_∧
(・д・ )
¬( )ゝ
.../ 〈
http://emoji.vis.ne.jp/hiiteshimauna2.htm