Trans wrote: > Doing some Javascript coding today and started to wonder about it's > open objects. If it works so well for Javascript, then why not Ruby > too? So I threw this together: > # Define a function. > > def fn(&b) > Func.new(&b) > end > > # Show off. > > if $0 == __FILE__ > > o = obj() > > o.a = 1 > p o.a > > o.b = fn{ puts "hello" } > o.b > > end > > So would Ruby benefit from being able to do this inherently? Or are > there reasons against it and it is actaully Javascript that's suffering > for it? Or is there some difference between Ruby and Javascript that > makes it good for one, but not the other? > > T. > Javascript is a prototype based language where prototype is a template for objects, Ruby on the other side is a class based language. It's nothing wrong with Javascript,IO,Self and others: http://www.dekorte.com/docs/protos/ or Ruby - they just represent different paradigms. But there are analogies as well: function Obj(){ } Obj.prototype = { attr : 7, method : function(){ print("hello!") } } The Obj prototype holds an associative array for new objects, so: obj = new Obj() obj.method() and this is pretty much an equivalent of a class based approach Ruby offers but when: obj.method = function(){ print("hello2") } obj.method() will print hello2. The _method_ attribute in object _obj_ now hides the original one (the one in prototype object) btw. This works pretty much the same in Python (there are dictionaries called __dict__ that hold attributes for classes and instances respectively). Ruby provides the same functionality using singleton objects class Obj def method p "hello" end end obj = Obj.new obj.method and then: class << obj def method p "hello2" end end obj.method the _method_ method is now being hold in the singleton class (the one you access by (class << self; self; end) ) there is also an implementation of a prototype-based Ruby sublunguage called sloop: http://chneukirchen.org/blog/archive/2006/08/sloop-sublanguage-for-object-orientation-with-prototypes.html lopex