Ruby, the purpose of the string replacement method

From [online ruby ​​documentation] [1] replace method of string class:

replace (other_str) → str Replaces the content and taintingness of str with the corresponding values ​​in other_str.

s = "hello"         #=> "hello"
s.replace "world"   #=> "world"

      

Questions:

1) what does it mean "depravity"?
2) What is the purpose of this method? Why use it instead of a simple one s = "world"

? The only idea I have has to do with pointers, but I don't know how this item is handled in ruby, and if so.

+3


source to share


1 answer


You are correct that it has something to do with pointers. s = "world"

will create a new object and assign a s

pointer to that object. While s.replace "world"

modifies the string object that is s

already pointing to.

One case where it replace

will matter when a variable is not directly accessible:



class Foo
  attr_reader :x
  def initialize
    @x = ""
  end
end

foo = Foo.new

foo.x = "hello"       # this won't work. we have no way to assign a new pointer to @x
foo.x.replace "hello" # but this will

      

replace

has nothing to do with tainted lines, the documentation just states that it handles tainted lines correctly. There are more efficient answers to explain this topic: What are Ruby's # taint and Object # trust methods?

+3


source







All Articles