[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: ANN: MetaTags 1.0

Dave Thomas

9/9/2003 4:00:00 AM


On Monday, September 8, 2003, at 10:35 PM, Yukihiro Matsumoto wrote:

>
> I agree with usefulness of user-defined literals, and this is much
> disciplined than generic reader macros, but still we need to discuss
> pros and cons.
>

A suggestion for a convention: rather than go down the strange
punctuation route (%Y{...} etc), could we just not adopt the convention
that, where sensible, each class that can construct instances from a
string should define a top-level method with the same name as the class.

So, if I wrote a class called Caml, I'd also define a top-level method,
also called Caml, something like:

class Caml
def Caml.from_string(str)
# .. check string format ..
self.new(str) # or something similar
end
end

def Caml(str)
Caml.from_string(str)
end


Then I could get the effect of literals using:

c = Caml "one hump or two"

If it was appropriate, the top-level method could be memoized, so we
could chose to have new objects created on each call or one object per
literal.


Cheers


Dave


1 Answer

Paul Brannan

9/9/2003 8:40:00 PM

0

On Tue, Sep 09, 2003 at 12:59:49PM +0900, Dave Thomas wrote:
> class Caml
> def Caml.from_string(str)
> # .. check string format ..
> self.new(str) # or something similar
> end
> end
>
> def Caml(str)
> Caml.from_string(str)
> end

A side-effect of this is that once all classes have a from_string
singleton method and a to_s instance method, I can now write:

class Object
def lexical_to(klass)
return klass.from_string(to_s())
end
end

which is similar to boost::lexical_cast in C++:

template<typename Target, typename Source>
Target lexical_cast(Source arg)
{
std::stringstream interpreter;
Target result;
interpreter << arg;
interpreter >> result;
return result;
}

(the actual implementation has a bit more than this with error checking
and such).

Paul