From: Robert Klemme Date: 2004-04-30T00:29:03+09:00 Subject: Re: Pointers in Ruby "Jean-Hugues ROBERT" schrieb im Newsbeitrag news:6.0.1.1.0.20040429160830.01b31568@pop.mail.yahoo.com... > At 19:14 29/04/2004 +0900, you wrote: > > >"Jean-Hugues ROBERT" schrieb im Newsbeitrag > >news:6.0.1.1.0.20040429071924.01cd1ef0@pop.mail.yahoo.com... > > > Hi, > > > > > > I am coining a Pointer class in Ruby. Kind of a C pointer, more > > > like a C++ smart pointer actually. Should work for any lvalue. > > > >Care to share what usage you envision for this? > > > >Btw: this rather looks like a reference than a pointer. As far as I > >understand, you create an alias for some variable (possibly a local var) > >as a handle to modify it from outside the original scope. Is that > >correct? > > > > robert > > Correct. But it should works for any lvalue not just variables. > i.e. ref{"a_hash[3]"} for example. > > > I initially named it a reference. But, references are usually automatically > dereferenced (they are more transparent than pointers). > > I could no find a way to do this in Ruby. That is why I am using the > []() accessor to get the referenced value. I'd simply use ordinary methods in the absence of an appropriate operator that you can use. class Pointer def deref() ... def deref=(x) ... end That's much more readable although a bit more typing. IMHO using [] makes it unnecessary difficult since it raises other associations. > This is very similar to > what you do in C with a pointer using * (content of). So, I eventually > renamed the class Pointer. I guess you mean "SomeType& operator*() const" etc. in C++. > Now, I may be wrong about the difference between a pointer and a reference > and I would be happy to change the code to something better. For the scenario you describe in the other posting I'd rather choose another approach, like holding all values in a hash and using symbols to reference them. That way, you can manipulate them easier IMHO. But that might be a matter of taste and of course I don't now other preconditions of your app... Example: class Var def initialize( env, sym ) @env, @sym = env, sym end def val; @env[@sym]; end def val=(x); @env[@sym] = x; end end env = { :x => true, :y => false } x = Var.new(env, :x) p x p x.val x.val = !x.val p x p x.val Your class LogicVar might even inherit this class. Or whatever is most appropriate in your situation. Regards robert