G
George Moschovitis
Note that EvilRuby has a less strict version of UnboundMethod#bind
wtf is EvilRuby ?!?!
-g.
wtf is EvilRuby ?!?!
-g.
George Moschovitis said:Robert,
thank you for taking the time to answer my post.
However, I dont think that this is a usefull example. One could use a
simple
obj.class.class_eval("..") to achieve the same.
Dont you feel that allowing bind to attach methods only to objects that
already have this method (ie, obj.kind_of(class) == true) is strange?
George said:Of course it has. Have a look at the following example:
class C1
attr_accessor :a
def a1
puts @a
end
def a2
puts 'hello'
end
end
class C2
attr_accessor :a
end
So for method C1#a1 the class C2 'quacks like a duck' (ie, it has the
attribute @a)
class Object
def cast(target_class)
copy = case target_class
when Class; target_class.allocate
when Module; dup.extend(target_class)
else target_class.class.allocate
end
instance_variables.each do |var|
copy.instance_variable_set(var, instance_variable_get(var))
end
copy
end
end
I do not think what you want has anything to do with 'duck typing'.
'duck typing' only means that you can send a message to any object and
if the object has a corresponding method it gets executed regardless
of object type. It does not urge you to abandon the "normal" way of
method definition for a class.
Gavin said:I do not think what you want has anything to do with 'duck typing'.
'duck typing' only means that you can send a message to any object and
if the object has a corresponding method it gets executed regardless
of object type. It does not urge you to abandon the "normal" way of
method definition for a class.
FWIW, in Javascript you can invoke a method defined anywhere with any
scope that you wish. For example:
Object.prototype.toString = function(){
return '['+this.constructor.name+' "'+this.name+'"]';
}
function Bird( inName ){
this.name = inName;
this.wings = 2;
}
Bird.prototype.fly = function(){
if ( this.wings )
{
this.altitude += 100;
alert( 'Look ma, ' + this + ' is flying!' );
}
}
function Pig( inName ){
this.name = inName;
}
var robin = new Bird( 'Tweeters' );
robin.fly(); // Look ma, [Bird "Tweeters"] is flying!
var super_pig = new Pig( 'Babe' );
super_pig.wings = 17;
robin.fly.call( super_pig ); // Look ma, [Pig "Babe"] is flying!
Bird.prototype.fly.call( super_pig ); // Look ma, [Pig "Babe"] is flying!
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.