From: Richard Kilmer Date: 2004-06-08T02:36:20+09:00 Subject: Re: How to ducktype a Hash? On 6/7/04 12:10 PM, "David A. Black" wrote: > Hi -- > > On Tue, 8 Jun 2004, Richard Kilmer wrote: > >> Moreover, if you could do that syntactically (ie. Change Ruby to support >> this kind of thing) like the following (love it or hate it) syntax: >> >> class Foo >> >> def {Hash}[](key) >> @mymap[key] >> end >> >> def {Hash}[]=(key, value) >> @mymap[key] = value >> end >> >> end >> >> f = Foo.new >> f{Hash}['name']="rich" >> >> ...but you don't always need the {...} >> >> p f['name'] => 'rich' >> >> ...and if you do something that's naughty... >> >> p f{Array}[1] => raise Exception... > > It would have to be something slightly different from that, though, > because of: > > irb(main):008:0> def f; [1,2,3]; end > => nil > irb(main):009:0> f{Array}[1] > => 2 > > > David Actually no...I don't think so. Ruby's scoping handles whether something is a method or a variable. If its a method, then: p f.class => Array p f{Array}[1] => 2 is correct because the [] method on the Array instance is correct (by default) in that f returns an array and you are calling: {Array}[1] On that object. Its a question of what you are sending the message to...in other words, the {...} is appended to the method that follows the } as 'semantic metadata', whereas with: f = Foo.new f{Array}[1] Is sending the message to the object pointed to by the variable f. So, where f is a variable or a method name, that is up to Ruby, but the {Array} data is attached to the method that follows, regardless. Its weird, because I am saying that you are kind of 'casting' the method itself rather than the object. -rich