Python vs. Ruby
There is a discussion on the net where people discuss Python vs. Ruby. The Ruby and Python Compared article started it, and here is a good answer article: Ruby misconceptions about Python.
I have both tried Python and Ruby and the languages are very alike, but yet a lot different. Python is more explicit - this gives clarity and more code. An example of this clarity:On Reddit a Ruby programmer posted some code that made building XML easy: def method_missing(name, attributes)
atts = attributes.map {|k,v| "#{k}='#{v}'" }.join(" ")
puts "<#{name} #{atts}>"
yield
puts "</#{name}>"
end
With that special method one can do following: div :id => "content" do
a :href => "reddit.com" do
print "reddit"
end
end
I wrote something similar in Python: import types
class Element:
def __init__(self, **kw):
self.elms = []
self.kw = kw
def __getattr__(self, name):
if name == "__getitem__":
self.elms = []
def add(l):
if type(l) == types.ListType: self.elms.extend(l)
else: self.elms.append(l)
return self
return add
def __str__(self):
attrs = " ".join('%s="%s"' % a for a in self.kw.items())
self.html = ["<%s %s>" % (self.name, attrs)]
self.html.append("".join(map(str, self.elms)))
self.html.append("</%s>" % self.name)
return "".join(self.html)
class Div(Element): name = "div"
class A(Element): name = "a"
Where one can do: print Div(id="content")[ A(href="reddit.com")["reddit"] ]
Functionality similar, but the way of achieving it is way different. Notice that in the Ruby case the "div" and "a" aren't defined and there is a lot of magic going on. In my Python code everything is defined explicitly. This approach gives a little more code, but better understanding. And that I think is the main difference between Python and Ruby. UpdateI have redone my Python version (functional style): def elmBuilder(name, **kw):
attrs = " ".join('%s="%s"' % a for a in kw.items())
def applyElms(*elms):
return "<%s %s>%s</%s>" % (name, attrs, "".join(elms), name)
return applyElms
def Div(**kw): return elmBuilder("div", **kw)
def A(**kw): return elmBuilder("a", **kw)
One can then do: print Div(id="content")( A(href="reddit.com")("reddit") )
My picnic in Lisp was well spent ;-) 10 comments so far
Post a comment
Commenting on this post has expired.
|
Blog labels |