From: Dmitry Bilunov Date: 2007-08-08T16:58:14+09:00 Subject: Re: non-constant strings Skye Shaw!@#$ wrote: > On Aug 7, 2:41 pm, Dmitry Bilunov wrote: >> if command.safe? > This will result in a no method error, no? It is just an example, assume that you have some safety-checking code here. > Well, this is not the fault of the language, rather your SecureRunner > class. Yes, it is not fault of Ruby, I am just trying to understand, why do the strings work in a such way. Most operations can be done with immutable strings - an operation can return a new string, constructed from method caller and, optionally, arguments. > This is the case any language where arguments are passed by reference. >> but what is the reason Ruby has non-constant strings > You mean mutable strings. Ruby does have constant strings: > > irb(main):001:0> CONST="assbasscass" > => "assbasscass" > irb(main):002:0> CONST=123 > (irb):2: warning: already initialized constant CONST > => 123 > > The String class wraps an array of chars, realloc()'in as necessary > (ruby hackers correct me if I've mistakin). Ruby string has array of chars, length (logical array size) and capacity (physical array size, probably larger, that logical) as Java's StringBuffer does. > > Consider this in Java: > > class SomeClassThatRequiredAlotOfTyping > { > private StringBuffer sb > //.... > public void printBuffer() { System.out.println(sb); } > } > > StringBuffer sb = new StringBuffer("Dont Chnage!"); > > SomeClassThatRequiredAlotOfTyping clazz = new > SomeClassThatRequiredAlotOfTyping(sb); > // I'll show that private "read-only" var who's in charge! > sb.delete(0,sb.length()); > sb.append("VB6, its ByVal keyword rocked... Not!"); > clazz.printBuffer(); > > Hope that helps. But Java has also String, not just StringBuffer. Is there anything like String to protect a program against such things? Or some version of .freeze, which freezes a variable (field) to anyone, except instance methods? -- Posted via http://www.ruby-forum.com/.