2008/9/5 Travis Warlick <twarlick / gmail.com>:
> I have implemented a sanitize! method into the String class to properly
> erase Strings from memory (example usage: clearing a password from memory),
> but I want to make sure that what I'm doing is actually doing what I think
> it is.

Copies won't be affected.  E.g. if you do

s1 = "...."
s2 = s1[1..-1]
s1.sanitize!

s2 will still hold most of the characters of s1. But there is no way
around this unless you want to resort to
ObjectSpace.each_object(String)...

> Basically, is this code going to leave _anything_ lying around in memory
> because of any undocumented/strange behavior or side effects of the []=
> method?
>
> class String
>  def sanitize!
>    for i in 0...self.length
>      self[i] = 0
>    end
>    self.delete!("\000")
>  end
> end
>
> Also, feel free to recommend any "better" ways to do this.

How about

class String
  def sanitize!
    gsub! /./, ' '
    strip!
    self
  end

  def sanitize_robert_paranoia!
    gsub!(/./) { (32 + rand(96)).chr }
    sub! /\A.+\z/, ''  # or slice! 0..-1
    self
  end
end

Kind regards

robert

-- 
use.inject do |as, often| as.you_can - without end