From: gabriele renzi Date: 2004-09-08T18:40:06+09:00 Subject: Re: [RCR] Unified type conversion framework Sam McCall ha scritto: > Cool! Occasionally I think about doing something like this, so I can > have some nice way to remember the custom conversions I use. I think most of us did, this is why I'm telling this is not something new :) > Maybe you could sneak some extra conversions in with it, like > [[1,2],[3,4]].as Hash # => {1=>2,3=>4} The system is open, I did thought of this when thinking how unintuitive Hash[anArray] is . This is another example of the need for a better approach, I guess there are much more ;) > Related to this is type-checking when you do want it (duck typing is > good, but I'd give it up in some cases to have an easy, readable way of > checking that I'm not passing a hash instead of an array). > I'd really like to be able to do: > def method(foo,bar) > foo.is! Hash > bar.can_be! Array > #... > end > where they do something like > def is! t > raise TypeError.new("Expected a #{t} but got a " + > "#{self.type}: #{self.inspect}") unless is_a? t > end > > def can_be! t > raise TypeError.new("Can't convert to #{t} from "+ > "#{self.type}: #{self.inspect}") unless can_be? t > end > > And can_be? is the does-this-conversion-exist method. #is! is broken, because it relies on is_a? that is not powerful enough to really express a type, but #as (or #to.. I mean, the proposed system) is powerful enough to expres any kind of type, including your #is! :) The same is said for can_be? Sure, I could introduce a method in the ConvTable that checks if a conversion path exists, but it won't work for, say, 'ciao'.as Integer because even if a String -> Integer conversion path do exist, you still have to check the whole string. So you end up needing #as again. > This might even be rdoc-able, if it was at the top of a method. It'd > certainly make the ad-hoc documentation I write today executable. exacylt what I was thinking of. The IdeaSpace is limited, it seem ;)