Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby, purpose of string replace method

Tags:

ruby

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

replace (other_str) → str Replaces the contents and taintedness of str with the corresponding values in other_str.

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

Questions:

1) what does it mean "taintedness"?
2) what is the purpose of such a method? Why using it instead of simply s = "world" ? The only idea that I have has to do with pointers, but I don't know how this subject is handled in ruby and if this is the case.

like image 200
AgostinoX Avatar asked Oct 23 '25 03:10

AgostinoX


1 Answers

You're correct that this has something to do with pointers. s = "world" would construct a new object and assign s a pointer to that object. Whereas s.replace "world" modifies the string object that s already points to.

One case where replace would make a difference is when the variable isn't 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 in particular to do with taintedness, the documentation is just stating that it handles tainted strings properly. There are better answers for explaining that topic: What are the Ruby's Object#taint and Object#trust methods?

like image 103
Max Avatar answered Oct 24 '25 17:10

Max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!