From: Robert Klemme Date: 2007-08-08T21:07:37+09:00 Subject: Re: non-constant strings 2007/8/7, Dmitry Bilunov : > Hello. Why does Ruby have non-constant strings? It seems there is a way > to bypass object encapsulation paradigm and break object integrity. Here > is any example: > > class SecureRunner > # This class implements a sudo-like > # runner > > def initialize(command) > # Creates an instance. Guaranties, that a command is safe. > if command.safe? > @comamnd = command > else > raise RuntimeError, "Security check failed!" > end > end > > def run > # Only safe commands should be run > system(@command) > end > end > > # This class seems to be safe > # Here is a way to bypass security check: > > command = "some_safe_command" > runner = SecureRunner.new(command) > # a command is safe, so check will be passed > > command.replace("evil_command") # BYPASS THE CHECK > > runner.run # runs evil_command, that is not safe That is easily fixed: # Creates an instance. Guaranties, that a command is safe. def initialize(command) # side effect free fix: command = command.dup # alternative fix: command.freeze if command.safe? @comamnd = command else raise RuntimeError, "Security check failed!" end end Now you can change the original string in as many ways as you like without doing any harm. As easy as that. And I'd like to add it's not the fault of the language if code like this fails. In fact there are numerous arguments in favor of having mutable *and* immutable strings vs. having mutable strings only. Kind regards robert