开发者

How does Ruby's replace work?

I'm looking at ruby's replace: http://www.ruby-doc.org/core/classes/String.html#M001144

It do开发者_如何学Pythonesn't seem to make sense to me, you call replace and it replaces the entire string.

I was expecting:

replace(old_value, new_value)

Is what I am looking for gsub then?

replace seems to be different than in most other languages.


I agree that replace is generally used as some sort of pattern replace in other languages, but Ruby is different :)

Yes, you are thinking of gsub:

ruby-1.9.2-p136 :001 > "Hello World!".gsub("World", "Earth")
 => "Hello Earth!" 

One thing to note is that String#replace may seem pointeless, however it does remove 'taintediness". You can read more up on tained objects here.


I suppose the reason you feel that replace does not make sense is because there is assigment operator = (not much relevant to gsub).

The important point is that String instances are mutable objects. By using replace, you can change the content of the string while retaining its identity as an object. Compare:

a = 'Hello' # => 'Hello'
a.object_id # => 84793190

a.replace('World') # => 'World'
a.object_id # => 84793190

a = 'World' # => 'World'
a.object_id # => 84768100

See that replace has not changed the string object's id, whereas simple assignment did change it. This difference has some consequences. For example, suppose you assigned some instance variables to the string instance. By replace, that information will be retained, but if you assign the same variable simply to a different string, all that information is gone.


Yes, it is gsub and it is taken from awk syntax. I guess replace stands for the internal representation of the string, since, according to documentation, tainted-ness is removed too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜