PDA

View Full Version : Python or Ruby?



thomasaaron
November 29th, 2006, 12:48 AM
Well, I'm starting to gain some momentum at programming Python. I've written an email merge program that is pretty awesome (if I do say so myself) and a couple of other neat programs. Now that I'm getting the hang of it, I hate to even consider switching to Ruby, but...

There's been a lot of talk lately about Ruby being the language (in its category) to beat. Linux Journal picked it over Python, too, in their Dec. issue of editor's picks.

So, really, I have two questions:

1. With the rise of Ruby, is Python going to be around for the long haul? While I'm just a hobbyist programmer, I would like to focus my attention on something with some longevity ahead of it.

2. Which language (of these two) do you guys prefer? And why?

Best,
Tom

atoponce
November 29th, 2006, 01:01 AM
Python is not going anywhere, despite the Rise of Ruby. Python is a solid language with a TON of benefits. However, I would rather learn Ruby, because of Rails. Other than that, no real factor would lean me one way or the other, and I think they're both staying around for the long haul.

ghostdog74
November 29th, 2006, 01:46 AM
So, really, I have two questions:

1. With the rise of Ruby, is Python going to be around for the long haul? While I'm just a hobbyist programmer, I would like to focus my attention on something with some longevity ahead of it.

2. Which language (of these two) do you guys prefer? And why?

Best,
Tom

Python started way before Ruby, that's why Ruby still rising.:D ..why don't you try Ruby? and decide for yourself later which one you like? There's no point asking other people because eventually, their choices is their own preferences. you have to got find your own.:D

fatsheep
November 29th, 2006, 04:12 AM
Both are great languages from what I've seen. I don't think you can go wrong either way but Python is more widely used by far. That may or may not be the case in the future as Ruby seems to be rising as has been said in this topic but at the moment Python is the big cross-platform scripting language.

ohgod
November 29th, 2006, 10:09 PM
I think fatsheep is right. I really like Python, and a colleague of mine swears by Ruby. I think they're both great choices, and both will be around for quite a long time. But because Python has been around much longer, you'd probably have better luck finding libraries with Python bindings, documentation, examples, etc. Plus Python is the preferred language for Ubuntu ;)

nereid
November 30th, 2006, 05:57 PM
There is just one point to consider if you want to learn Ruby. Matz and Company are currently working on Ruby 2.0 and there will be some changes to the syntax and to the language in general. This means that you'll have to learn some new things with Ruby 2.0 whereas Python won't change anymore.

JeffS
November 30th, 2006, 11:20 PM
I'd say go for Python. It's much more mature, better supported, has more libraries - just look at all the pyGTK programs over at the pyGTK website, then add the wxWidgets apps, then PyQT, then Zope, then Google's usage (Python creator and BDFL Guido Van Rossum is employed by Google), NASA's usage, and Industrial Light and Magic's usage.

Ruby is nice too, especially for Rails. But Python's reach is far more prevalent.

And Python is very easy to learn and use, and the syntax is very readable and clean, and by extension very very maintainable.

Finally, I like Python's extreme flexibility. It's great for data munging, a la Perl, it's great for Web (with stuff like Zope, mon_Python), a la PHP, it's great for desktop apps (pyGTK, PyQT, wxPython), it has interfaces into both Java and .Net (Jython and Iron Python, respectively), it's great as a "Glue" language, it's great for XML and web services, it's great for database apps, and finally, it's damn fun to program with Python.

The only traditional knock on Python is speed. It's not the speediest kid on the block. However, that is just pure, raw code execution speed. Overall perceived speed has many other factors. For instance, both Java and C# have superior raw code execution speed (with the JIT compilers, and byte code interpretation), but both the Java and .Net virtual machines are huge memory and CPU hogs. By contrast, the Python interpreter seems downright small and efficient, not using all that much memory. Thus, in my experience, Python apps launch quicker, and are generally snappier than equivalent Java or C# apps.

For a high level dynamically typed language, it's hard to go wrong with either Python or Ruby. In fact, both are probably better, all around, than Perl. Perl is powerful and efficient and extremely flexible, but it gets messy and ugly and hard to maintain over time, especially as a Perl script or program grows in size, and is changed/added on to by different programmers. PHP is fantastic for web programming, but has not made any impact in any other arena.

f all the big open source scripting languages, that leaves both Python and Ruby as the best "all-arounders", especially Python. Python as truly been applied very successfully in pretty much all application domains, sans full on systems programming (OS kernels, drivers, hard core games, scientific processing, etc), where C and C++ are kings.

In my programming career, I have more or less ignored Python. But not now. Can you tell I'm pretty high on Python?

coder_
December 1st, 2006, 04:07 AM
Really, it depends what you want to do with it.

I find that web development is heavenly with Ruby and RoR. (http://rubyonrails.com/)

But, GUI programming is really nice with Python and PyGtk, and I think CLI programming is better in Python too.

Both are really nice, neat, and easy languages to learn. Personally, I'm a language freak. I love to design, implement (Not so great at this yet), use, and just poke around in all the languages I can find. It's quite odd how my love of languages is non-existent in the real world though. I hate learning foreign languages, but love learning programming languages :P

pmasiar
December 4th, 2006, 09:05 PM
With the rise of Ruby, is Python going to be around for the long haul?

Google hired many top Python developers. And someone said Google does not want to promote python too much, because then competition could start using it too :-) Python is here to stay. Long after ruby zealots will move to something newer, cooler.

Ruby got big boost from Rails, simplified web application framework. Python had about 30 frameworks competing, but after Google hired Guido (python's father) and made him to program for web, dust settled a little. Winners are Django, TurboGears and pylons.

You know that Python is designed for readability. It just fits my mind. Ruby is much improved perl, with more quirks.


While I'm just a hobbyist programmer, I would like to focus my attention on something with some longevity ahead of it.

Which language (of these two) do you guys prefer? And why?

I just answered this question in another thread:
http://ubuntuforums.org/showpost.php?p=1844537&postcount=14

You may want to read especially "the hundred-year language": http://www.paulgraham.com/hundred.html about why we will be using language like python 100 years from now.

addicted68098
December 4th, 2006, 10:44 PM
Ruby seems like it would be painfully slow, but I really can't say much because I have never actually tried ruby. I like python for its clean syntax and ease of use, its also fun to write, ruby also seems fun to write, I am installing ruby now.

asimon
December 5th, 2006, 09:38 AM
whereas Python won't change anymore.
Actually Python, as every language with active development, changes all the time. Just have a look at What's New in Python 2.4 (http://www.python.org/doc/2.4.4/whatsnew/whatsnew24.html) or What's New in Python 2.5 (http://docs.python.org/whatsnew/whatsnew25.html) to see what changed in these versions.

I would call a language which doesn't change anymore dead.

AdamG
December 5th, 2006, 11:46 AM
I'm going with Python.

IMHO, Python is the best general-purpose language out there. Ruby probably is better for web applications, and PHP is probably better for web scripting, Perl is probably better for text processing, etc. But they all pretty much suck at each other's niche.

But because Python's been actively used for so long, it has an incredible library which means it is pretty good at a large number of things. If you learn python, you can do everything from funky 3-d graphics to simple scripting. Nothing else (that I've worked with) offers that level of versatility. It's a fantastic first language to learn, because although it is among the least dogmatically hard languages, it will take anyone a long time to outgrow it.

On the other hand, learning Python first means you don't realize how good you have it. Learning Java was a series of dissapointments for me. :-#

Burgresso
December 9th, 2006, 04:52 AM
Go with Python!!!

Ruby is a fine language - but the only reason we are talking about it b/c of Rails. Rails will cool off - if it hasn't began to allready - b/c of its difficulties in handling large traffic and because of diffeculties in setting up. It's a pain.

I like to think if have some insight on this as I'm a web developer. Ruby will always be around, but it won't always be "hot". This is just my opinion, though.

loell
December 9th, 2006, 05:11 AM
i think there was, there was an informal benchmark, that django is faster than rails.

rails has a more comprehensive documentation than django, but its about to change when the django book will be release.

asimon
December 9th, 2006, 01:16 PM
Ruby is a fine language - but the only reason we are talking about it b/c of Rails.
Rails will cool off - if it hasn't began to allready - b/c of its difficulties in handling large traffic and because of diffeculties in setting up. It's a pain.
Setting up Rails is dead easy, much more than say TurboGears, but okay, there are respective mailing lists where the nice gurus hang out so everyone having problems can easily find answers if he cares.

Anyway, you don't have to look at Rails at all to like and appreciate Ruby. It's a great language to use without Rails or any Web stuff. Just visit ruby-talk to see the many many non-web projects where people use Ruby.



I like to think if have some insight on this as I'm a web developer. Ruby will always be around, but it won't always be "hot". This is just my opinion, though.
Yes, but what's the point? Depending on your definition of 'hot' Python is not hot, or at least -- as all things -- will not stay hot forever too. 'Hotness' is surely not the best reason to use any language, and hinting that people use Ruby just because the 'hotness' of Rails doesn't do the language justice.

asimon
December 9th, 2006, 01:26 PM
i think there was, there was an informal benchmark, that django is faster than rails.
True, but that should not be overestimated. I doubt that these differences in run-time performance matter for most projects. And for those where performance is a big factor there are most of the time even faster options then django.



rails has a more comprehensive documentation than django, but its about to change when the django book will be release.
There are already several Ruby on Rails books available. It will need much more then a single Django book next year to change the situation.

loell
December 9th, 2006, 02:26 PM
like i said, ruby has a comprehensive documentation, and that includes all freely available e-books of RoR ,

but given the large userbase of python , more pythonistas will use python as webframework when django documentation is made complete and available.

Burgresso
December 9th, 2006, 06:00 PM
True, but that should not be overestimated. I doubt that these differences in run-time performance matter for most projects. And for those where performance is a big factor there are most of the time even faster options then django.

Ruby is slower than javascript.

I've never said or implied Python was a trendy language; it's not.

There can be diffeculties setting it up on apache; hense the popularity in mongrel.

gummibaerchen
December 9th, 2006, 07:36 PM
I started with Ruby, and you will love it the first time.

You have tons of starter tutorials and so you have really a kick-start and have your first 100 Apps in just a week.

But most of this works like "magic", if you then go and try to understand it you just can't.

I'm much happier with Python. Even if I may sometimes have a line more of code (doesn't happen often) I can at least read it as easy as a photoalbum :)

gga73
December 12th, 2006, 05:51 AM
My guess, no, as ruby is indeed a better thought out language. But... there's enough python already written that is not going to vanish (and some large companies did invest heavily onto Python -- google, ilm, etc). Ruby is just as old as python, albeit it was really brought into the West later than python.

[QUOTE=thomasaaron;1819618
2. Which language (of these two) do you guys prefer? And why?


Ruby, by far. Several reasons.
While python's rigid syntax is an attempt to try to make coding consistent across developers, in large projects I can tell you it is all a big lie and in practice this doesn't happen. By enforcing tabulation with its syntax, python makes it much harder to use one of the most important features of dynamic languages, which is their ability to eval() their own code to create routines on the fly.
This also prevents python from being used as a language for domain specific languages (an area where ruby excels at). This makes it impossible to have something like ruby on rails implemented in python, without having to write your own parser/mini-language.
For a language that brags about its readability, Python's overloading of operators and main methods (__getattr__, __init__) are painful on the eyes. Python's lambda constructs are also horribly to read compared to ruby's blocks.
Python's lack of built-in regex makes it pretty painful to use for sysadmin tasks or one-liners, unlike ruby.
Python also uses a multi-inheritance model for its OO. This is a plus over ruby but it is a mistake, imo. Over the years, I have learned that multi-inheritance is unneeded, and that a model based on single inheritance with mix-ins is a better approach.
Python's list comprehensions and generators are a brilliant idea, but their syntax is also painful and I personally find it unreadable. (ruby has inject which does the same, but the current interpreter does not do the kind of optimizations that python does with list comprehensions).
Python makes its interpreter also be its interactive terminal. Again, this is a mistake, as it prevents users from easily configuring it or expanding on it (this forced python users to eventually create their own interactive terminals). In comparison, ruby's irb is much less useful out of the box, but much more productive after a year of use (well, with wirble, you now get it more productive after 5 mins now :). Of course, if you are using an IDE for either language, this is probably not so important to you.
What is important to interactive testing is Ruby's ability to open classes at any time. This very easily allows you to add/change methods from classes and instances and do introspection for debugging.
Python's built-in library is badly organized and inconsistent. Python lacks upgrading third-party libraries in a painless manner compared to ruby's rubygems, python is several years behind. But python, having reached its popularity sooner, means it still has more libraries available to it.
Ruby is OO through-out from day one, unlike python's OO which was bolted on later on. This shows in pythons silly need to have self as a parameter to each function and forcing developers to write self.something when referring to an attribute.
Of course, the biggest benefit of Ruby's OO is that the syntax of the language makes the distinction between functions and attributes be non-existent. This is a feature that allows large projects to be much more easily developed and maintained in ruby than in python.
Ruby OO also supports the concept of public, protected and private. Again, much better for large projects or libraries.

Ruby's current main disadvantages against Python are: lack of invoking functions with named parameters (feature to be added Dec.2007) and that method objects are a tad more painful to use than in python. Ruby's performance is currently also about 20%-30% slower (albeit this disadvantage is already gone if you are using YAML which is expected to be officially released around June2007 and be part of Ruby's C interpreter December2007).

David Marrs
December 12th, 2006, 10:13 AM
I would call a language which doesn't change anymore dead.
Whereas I'd call it mature.

almahtar
December 12th, 2006, 10:36 AM
I always knew smalltalk would beat Java in the end. I just never thought it'd be called Ruby when it did
That's a quote from an OO guru whose name I've forgotten. I've messed with a lot of OO projects: Ruby projects have always impressed me the most.

pmasiar
December 12th, 2006, 05:31 PM
My guess, no, as ruby is indeed a better thought out language.

LOL!!! python and ruby are rather similar. Ruby is closer to OO perl (http://www.rubygarden.org/faq/entry/show/14). Same quirks, same reliance on special characters for syntax, same reliance on magic from cowboy programmers. I understand people love perl or ruby, but (after having to maintain bunch of perl code written by other people) I learned that magic will come back to bite you. One of the reasons why java is so popular in industry that it has bland, predictably formatted code, so outsider can jump in and modify it. Ruby is more OO, but goal of python was not be more OO: goal of python was being readable and predictable.


While python's rigid syntax

LOL again. First thing I do when I am taking over of someone else's code, is to make sure it is properly aligned. Rigid syntax means you cannot cheat with alignment - alignmebt *is* syntax. I know it is unusual and it took me some time to get used to, but when I realized I do it anyway - why to fight it? And it saves many lines with just closing braces. Less wasted space on my screen.


in large projects I can tell you it is all a big lie and in practice this doesn't happen.

I have no idea what are you talking about. Alignment *is* syntax, program with wrong intendation will not compile. Or are you talking about variable/functions naming conventions? How that is relevant to language design?


By enforcing tabulation with its syntax, python makes it much harder to use one of the most important features of dynamic languages, which is their ability to eval() their own code to create routines on the fly.

You obviously missed eval (http://docs.python.org/lib/built-in-funcs.html)function. Allows to evaluate either code string, or , citing documentation: can also be used to execute arbitrary code objects (such as those created by compile()) Python has also exec(), execfile(), and compile(). I understand you may like ruby more than python, and I have no problem with that. But *you are quite obviously ignorant about python* - so why you feel competent to pass expert judgements and criticize something you do not understand?


This also prevents python from being used as a language for domain specific languages (an area where ruby excels at). This makes it impossible to have something like ruby on rails implemented in python, without having to write your own parser/mini-language.

For a language that brags about its readability, Python's overloading of operators and main methods (__getattr__, __init__) are painful on the eyes.

LOL again. You are really making my day today. Operator overloading is exactly the feature making small domain specific languages (http://en.wikipedia.org/wiki/Domain_Specific_Language) easy in python.

I am no way a ruby expert - but from what I've seen, there is no big difference from perl. No magic bullet. Or did I missed something? Enlighten me - links please.


Python's lack of built-in regex

LOL LOL! see module re (http://docs.python.org/lib/module-re.html) which is part of standard library. Decision was; make it standard, but don't pollute language for people who don't need it. Personaly I use string methods like .startswith() more often for 80% of what I do, and it is *more readable*.


makes it pretty painful to use (python) for sysadmin tasks or one-liners, unlike ruby.

Obviously. Python consciously decided to *not* be language for admin's one liners - noone can beat perl in that game, and why in the hell would you want to? Did you ever played perl golf (http://en.wikipedia.org/wiki/Perl_golf#Fun_with_Perl) competition? Can you write haiku in ruby? In perl you can. Does it mean perl is better?


Python also uses a multi-inheritance model for its OO. This is a plus over ruby but it is a mistake, imo. Over the years, I have learned that multi-inheritance is unneeded

LOL!! Ridiculous. If you don't need multiple inheritance, dont use it. It does not hurt you until it is needed. *Then* you need it big time. Your arguments do not make sense to me. It is like: "I like my shackles - the hurt only a little, and only if I try to walk, it is fine in I don't walk". Nonsense.


Python's list comprehensions and generators are a brilliant idea, but their syntax is also painful and I personally find it unreadable.

Well, i pesonaly find unreadable ruby's statement modifiers, and optional keywords, and inheritence from perl: difference between $ and @ is plain confusing. I know how to handle it (did it in perl) but I ask: why?


Python makes its interpreter also be its interactive terminal. Again, this is a mistake,

You *really* like your shackles. Don't use shell if you don't like it. Personally I consider it one of the *best* features of the python: you can import modules, instantiate objects, look at object methods, follow some tutorial one line at a time, looking at your objects from all sides. No need to write one-off test programs just to try how some feature works.


as it prevents users from easily configuring it or expanding on it (this forced python users to eventually create their own interactive terminals). In comparison, ruby's irb is much less useful out of the box, but much more productive after a year of use (well, with wirble, you now get it more productive after 5 mins now :).

So you concede python is better out-of-the box (for a beginner). If you need more, use IPython (http://ipython.scipy.org/moin/) interactive shell. But I do not understand: What is the use case? I try functions in terminal, then write real program code to use it.


What is important to interactive testing is Ruby's ability to open classes at any time. This very easily allows you to add/change methods from classes and instances and do introspection for debugging.

You want to suggest that python lacks object introspection? It's no surprise that you would be wrong again. Or is it something else I am missing?


Python's built-in library is badly organized and inconsistent.

yet another expert opinion from a python expert. :-/


But python, having reached its popularity sooner, means it still has more libraries available to it.

*Much* more libraries. I know about people moving from ruby to python because of lack of the libraries.


Ruby is OO through-out from day one, unlike python's OO which was bolted on later on.

You must mistake perl with python. Python was OO from day one, nad had conscious decision to add self as a parameter.


This shows in pythons silly need to have self as a parameter to each function ... Of course, the biggest benefit of Ruby's OO is that the syntax of the language makes the distinction between functions and attributes be non-existent.

This shows our expert misses difference between a function and method. No wonder: it is non-existent in Ruby :-) Python method uses function-like syntax, adds *self* (or *this* or *it* or whatever you prefer) to reference your object. Ruby decided it is worth special keyword. Matter of opinion and taste. We don't burn people at the stake for such things anymore.


Ruby OO also supports the concept of public, protected and private. Again, much better for large projects or libraries.

As Larry Wall famously said, he prefers you not sleeping in his living room because you asked you so, not because he has a shotgun. Private variable is a shotgun. Python has *convention* to name variables intended as private with prefix: _name. It means, please dont use it unless you know what you are doing. We are consenting adults. I will preprocess code with [*#def private public* to access your "private" variables if I have to: I have the source. :-)

Summary (whew it was long): opinions, personal taste, misunderstanding and misinformation. Is ruby community this desperate? I believe ruby is decent language for someone willing to put up with it quirky perl-like syntax and is not hurt by lack of libraries and slower speed. Ruby has good app: rails. Python community did not started smear campaigh agains Rails, but accepted the challenge and created *two* great rails-like frameworks: Django and TurboGears.

Our competitors are not other free scripting languages: competition is closed-source enterprisey mamonths.

gga73
December 25th, 2006, 08:37 AM
Okay... you asked for my qualifications. So I'll start with that. I've been coding for the past 20 years. I've coded Ruby for 2 years, Python for 3 (and know about it for 5), Perl for 5 years, TCL for a year, C/C++ for 7, shell scripting for much longer, etc. I also know Logo, BASIC, assembler and probably others I've forgotten.
Now, those 3 years of dealing with python were done at ILM (one of the largest python places in the world), so I know very well what python can achieve as well as where it fails miserably.

That being said, I sustain ruby is a better language.

I'll clarify and prove my points, but first...
I recommend you download or read on-line "Programming Ruby". That way, you'll be able to criticize it properly.
Now, since you are likely also using Ubuntu, getting a proper standard ruby distribution is a tad hard, as Debian splits packages in a lot of ways. You need to do:


> apt-get install ruby1.8 libruby1.8 irb1.8 ri1.8
# add ruby1.8-dev and libruby1.8-dev for development, too

Okay... now you have a proper ruby distro to start playing with.
To try some of snippet of ruby code, you may want to try:

> irb
# And now you can type ruby code.

Irb by default is relatively plain.
To customize irb (add colors, completion, help, etc), the easiest way is to install wirble.
I'll do that by installing rubygems first, which is ruby's now more or less standard way of distributing libraries (it is to become part of ruby's core eventually).

You can get rubygems from www.rubyforge.org. That site also contains most of today's ruby libraries (around 2600 -- so much for few ruby libraries).
rubygems is a tad different to install. After unzipping it, you cd to its dir and you'll need to do:

> ruby extconf.rb
> make
> sudo make install

Once rubygems is installed you may want to now install wirble (or any of ruby's libraries):
> gem install wirble

For docs on wirble, you want to look at:
http://www.rubyinside.com/wirble-tab-completion-and-syntax-coloring-for-irb-336.html

Wirble allows irb to show syntax coloring, tab completion, etc (lots of customization).

Now, to answer your comments...


Ruby is closer to OO perl.

Ruby and Python are indeed similar.
However, Ruby's OO is most-definitively not like Perl... AT ALL!
Ruby's OO is single-inheritance with mix-ins.
This makes Ruby's OO very similar to Smalltalk's, with mix-ins being similar to Java's.
Its syntax, however, is much more closer to python than to Java, Perl or Smalltalk.


Ruby is more OO, but goal of python was not be more OO: goal of python was being readable and predictable.

Ruby's goal was to make programming fun. Ruby users often refer to it as following the Principle of Least Surprise (POLS).
As such, Ruby is both readable, predictable and has copied all of the good features of Python, Perl and Smalltalk.
Amazingly, Matz (its creator), succeeded at doing so. It could have easily been a mess.


Regarding Python's syntax, white space, and the like...

Python's syntax is very rigid. For example, you cannot do:

a = 20 if x == 20
which is relatively common construct found in C, Perl, Ruby, etc. You cannot also do things like do/while constructs, instead of while/do constructs. You don't have switch statements. The list goes on.
Ruby is much more flexible in this sense, while at the same time, not as crazy flexible as Perl is.


You obviously missed eval function.

No, I didn't. Have you tried using it much in python? I have, and was extremely dissatisfied with it. Here's a place where tabulation comes to haunt you.
If you just eval a single command, there's nothing wrong with it.
However, if you try to start eval'ing code that is several lines long, with ifs/whiles/etc., it is a nightmare compared to Ruby's eval. You have to make damn sure your code is tabulated properly at all times. This more or less forces you to need to pass a tabulation variable or parameter to every function that creates code on the fly to later be evaled... to make sure the code actually *COMPILES*.
Not surprisingly, eval() is not used much in python code.
Now I consider the ability to eval code on the fly one of the main attractions of dynamic languages, and python just takes that feature and makes it very hard to use.
Now, for good examples of how evaling long code can be useful, I can recommend looking at Getopt/Declare in Perl or my port of it in Ruby.
For other examples, Ruby on Rails and DSLs are a good examples of using other eval constructs.
Doing something like that in python is possible, but it is much, much, much harder,


See module re

Yep, familiar with it and also with its distant cousin the regex module.
Problem is, they are not built-in.
Thus, every regex comparison in python usually is divided into 2 or 3 annoying steps (a 4th if you include the import too): create the regex, use it to compare it and find the match results. A typical regex code in python looks like:


import re
r = re.compile(r"^([a-z])", IGNORE_CASE )
m = r.match( string )
if m:
print m.group(1)


Here's the equivalent Ruby code (Perl's regex is similar):

puts $1 if /^([a-z])/i

Not only is Ruby's approach more readable, but it is also shorter. Before you complain, let me mention that Ruby's regex, unlike Perl's are also objects. So you can also use Regexp objects and MatchData objects with all the standard ruby constructs.



Operator overloading is exactly the feature making small domain specific languages easy in python.

Err... no. Compare Python to Ruby:

Python:


# As numeric
class N(Integer)
def __mul__(x):
return x * self

# As array
class A:
def __getitem__(self, idx ):
pass
def __setitem__(self, idx, val ):
pass



Ruby:



class N < Integer
def *(x)
x * self
end
end

# As array class
class A
include Enumerable # gives you ALL of ruby's array methods ( a mix-in )
end

# more selectively, you can still do...
class B
def [](idx)
end

def []=(idx)
end
end



I think you'll find the Ruby's version simpler. No need to learn what __mul__, and the other 20+ python constructs are. I always screw it up in python ( I use mult instead of mul, for example).
With ruby, I never do. It is the same syntax that I use when using the method :)


I am no way a ruby expert - but from what I've seen, there is no big difference from perl. No magic bullet. Or did I missed something? Enlighten me - links please.

Hell, no. Ruby is WAY above python or Perl in this.
Okay... this one is hard, as DSLs do require a better grasp of the language (took me a year in ruby to "get" it).
But... I'll mention the features that makes DSLs in ruby so nice:
a) Ruby's functions/methods can be invoked without parenthesis.

message("hello, this is an example in python")

message "hello, and this is in ruby"

b) Ruby supports blocks, python doesn't.

This is an actual ruby DSL (it is ruby code) I've developed for managing 3d renders:


render {
scene "hello.ma"
frames 1..9, 30, 20
overrides {
layer "beauty" {
antialias 3
}
}
}

c) Besides "eval", ruby supports instance_eval() and class_eval(). This allows evaling a piece of code within the frame of reference of another class or instance.

d) Ruby's methods (and functions) support special characters in their names, like ?, !, etc.


class A
def has_data?
# do something here
end
end

a = A.new
if a.has_data?
end

e) Ruby makes it easy to open built-in classes and add methods. For example:


class String
def no_spaces
return ! include? ' '
end
end

puts 'This should have no spaces'.no_spaces


Compare that to Python, which still struggles with some of this:



def no_spaces(self):
if (' ' in self):
return False
return True

str.no_spaces = no_spaces

print('This should have no spaces'.no_spaces())
>> TypeError: can't set attributes of built-in/extension type 'str'

When you combine all of these, you can easily build a DSL that feels like a English (or most western languages). For a tutorial, I recommend:
http://www.artima.com/rubycs/articles/ruby_as_dsl.html
Up to page 2 or so, it is stuff you can also easily do with python. Pages 3 and 4, I'm not sure how you do them in python.
Other good examples in ruby include Rake and, to a lesser extent, Ruby on Rails.



Obviously. Python consciously decided to *not* be language for admin's one liners - noone can beat perl in that game, and why in the hell would you want to? Did you ever played perl golf competition? Can you write haiku in ruby? In perl you can. Does it mean perl is better?

Actually, Ruby matches Perl's one-liners, no problem. Most of Ruby's switches match those of Perl. Thus, to put the regex we wrote to good use, you can from a shell do:



> ruby -ne 'puts $1 if $_ =~ /^([a-z])/i' < yourfile.txt


and get the first letter of each line. Any sys-admin that knows ask or perl can easily dive in to write ruby one-liners in just seconds (or easily replace those written in those languages)
And yes, this does mean Perl is better than python for sys-admin tasks. But Ruby is better than both :)



Don't use [python] shell if you don't like it. Personally I consider it one of the *best* features of the python: you can import modules, instantiate objects, look at object methods, follow some tutorial one line at a time, looking at your objects from all sides.


You seem to not realize ruby has all that, too :)
Just better. With IRB, you can also:
- avoid rewriting classes to just add a method.
- see your output in color
- use tab completion
- add more customizations in your .irbrc file.

The equivalent in python is, as you mentioned, IPython, which has over irb only the ability to run the debugger.
The beauty of ruby in this aspect is that since IRB is a standard ruby module, it can easily be used within other contexts (as a shell for ruby in embedded programs, etc). I have not looked at IPython in detail, but I imagine doing so will be difficult in it.


So you concede python is better out-of-the box (for a beginner)

Hell, no! Teach them ruby instead! They'll find it easier and will probably end up writing better code in the long run.
Now, if you are using Ubuntu, as you probably are, python currently does come properly pre-installed. Ruby now also ships with Ubuntu, but mainly for amarok, not as a real language (read above to download all you need to get a proper ruby distro in Ubuntu).


You want to suggest that python lacks object introspection? It's no surprise that you would be wrong again. Or is it something else I am missing?

Python does lack some introspection. I already showed you the problem of not being able to open some of the built-in classes like str (a pretty important class, I might add).



Ridiculous. If you don't need multiple inheritance, dont use it. It does not hurt you until it is needed. *Then* you need it big time.

Actually, multiple inheritance has more or less now be proven not to be needed. That's coming from people who have used multiple inheritance in other languages for years (C++, mainly).
Most of the features of multiple-inheritance can often be solved with mix-ins, and in the very weird case it can't, you can implement multiple inheritance with dispatching.
This makes the code much easier to maintain in the long run, as there's less head-scratching once you invoke a method and it does not do what is expected (and you are trying to figure how the diamond inheritance chain is working).
Other than that, I would be glad to hear of a project that actively uses multiple inheritance and could not be done without it.


Well, i pesonaly find unreadable ruby's statement modifiers, and optional keywords, and inheritence from perl: difference between $ and @ is plain confusing. I know how to handle it (did it in perl) but I ask: why?

Ah... I see. You never actually USED ruby, and you are just basing your criticism on misconceptions and hear-say. Not sure what are ruby's statement modifiers or optional keywords are.
Inheritance has nothing to do with Perl, as I already explained.

$ and @ is VERY straight-forward. $ are global variables, @ are instance variables. Global variables are hardly used except for the main regex variables. @ are used, but only within classes, like you do with self.x in python (same meaning). Local variables don't have any qualifiers.

This has NOTHING to do with Perl, which uses: $, @, %, for scalar, array and hashes and \$, \@, \% for references to such (and classes are also $ and \$), and which are found all over perl's code.



*Much* more libraries. I know about people moving from ruby to python because of lack of the libraries.

I know of *NOONE* doing so, and certainly not because of libraries. In what domain? I'll make a bet and say you are trolling.
For each python library you mention, I'll see if can show you an equivalent (or better) ruby library. My guess is that you'll need to find something pretty obscure, as most standard stuff is there (command-line parsing, vector/matrices, numpy, sdl, opengl, widget toolkits, etc)
As for the opposite, I've already mentioned one library not available in python (Getopt/Declare).
Perl is the only language that can truly boast to have more libraries than others (which is also somewhat of an inconvenience as it becomes hard to choose among them).


You must mistake perl with python. Python was OO from day one, nad had conscious decision to add self as a parameter.

In this, you may be partially right. Python 0.95 did not have OO, but once it got added, it came with self. Why self was chosen, however, remains somewhat a mystery, as other OO languages at the time did without it.
Note, however, that Python's OO did change (super, for example, did not make into python until much later, albeit it was always part of ruby).

Regarding differences between attributes and functions...


This shows our expert misses difference between a function and method. No wonder: it is non-existent in Ruby Python method uses function-like syntax, adds *self* (or *this* or *it* or whatever you prefer) to reference your object. Ruby decided it is worth special keyword. Matter of opinion and taste. We don't burn people at the stake for such things anymore.

Besides your comment being very aggressive, I'll say it nicely, but you are dead wrong here.
Ruby does indeed not distinguish between a function and a method. This is more a matter of naming, as python's functions+methods == ruby's methods.

However, my comment was about attributes (ie. class/instance variables) and functions/methods.
I'll show you some code within an irb vs. python session to prove why ruby's approach is much better, with my comments. This is all done within a single ruby session, btw...



#
# Let's create a class with one attribute (x)
#
class A
def initialize
@x = 10
end
end

a = A.new
a.x
NoMethodError: undefined method `x' for #<A:0x2b9b81551d68 @x=10>
from (irb):20
from :0

# You'll notice that you cannot get to the a.x attribute. This is a GOOD thing.
# Attributes in ruby are PRIVATE by default.
# It keeps the class encapsulation and prevents users from misusing your class.
# For this example, I don't want x to remain private, thou.

class A
attr_accessor :x
end

a.x
10

# attr_accessor is a function that adds a getter and setter within ruby.
# You can think of it as a macro that creates two member functions, one for reading
# the x attribute and one for writing it.
# Now, the class behaves like your average python class and any user can access
# the value of x by calling a.x

#
# In Ruby, if I call an attribute that does not exist...
#
a.xx
NoMethodError: undefined method `xx' for #<A:0x2b83d871da68>
from (irb):7

#
# which is a good thing. No way to screw things in the class or in my code due
# to a typo or misuse.
#


#
# However, let's suppose that in the course of developing my application
# I decide that x should be a calculated value instead of a simple attribute.
# I'll show you the beauty of ruby here...
#

class A
def x
@x * 20
end
end

a.x
200

# Now, in case it is not obvious, I just re-created the x reader member function with
# my own code. However....
# I STILL remain accessing it as a.x, like an attribute. NONE of my other code that
# is using class A needs to be modified!
# What's more... I did it globally to ALL instances of class A.

# Now, doing things globally is a tad dangerous. If this was part of a nuclear
# reactor and class A was a fundamental class in its operation, I could have
# screwed things up. If I wanted to test things locally, I could do something like:

class << a
def new_method
'this exists on a only'
end
end

a.new_method
>> this exists on a only

b = A.new
b.new_method
NoMethodError: undefined method `new_function' for #<A:0x2b9b80bc8d28 @x=10>
from (irb):28
from :0

#
# So you see... my 'a' instance has that method but all other A classes don't.
# Now *THIS* is the power of ruby.
#


For comparison and to show you how poor python is, I'll try to do something similar in it:



class A:
def __init__(self):
self.x = 10

a = A()
a.x
10

#
# Now, here you see how python is already breaking encapsulation and does not
# have any idea of what private is. All your attributes are exposed publicly by default.
# This is DANGEROUS.
#
# Worse, in python you can do:
#

a.xx = 20

#
# And now your instance also has an xx attribute!!!
# So much for proper OO. This breaks COMPLETELY the whole concept of OO, which is
# to keep data private as much as possible within a class.
# A very simple typo in your code in Python can lead a function mis-behave, as you
# just create a new attribute in your instance!!!
#

#
# Okay... now say I've been using the A class for long and realize that instead of x
# I need to change it to return a calculated value.
# I'll try the logical thing first.
#

def x(self):
return self.x * 20

A.x = x
a.x
10

#
# No such luck. Python does not allow me to override the attribute.
# Worse... my x() function is nowhere to be found.
#

a.x()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'int' object is not callable

# Silly python wants to call 10() -- ain't that smart?

# I can work around that by placing it as another function, like:
A.t = x
a.t()
200

# But, you still have the problem that:
a.x
10

# is STILL accessible to outside parties, and all your code would need changing.
# Not good.
#
# The other approach in python is using __getattribute__
# I'll redefine class A to start from scratch now.
#

class A(object):
def __init__(self):
self.x = 10
def __getattribute__(self, attr):
return object.__getattribute__(self, attr ) * 20

a = A()
a.x
200

#
# Now... See all the problems?
# a) Syntax is horrible.
# b) It forces me to make my class inherit from object... what if I had defined it without it?
# c) But worse, the __getattribute__(self, attr) method is a single point of access for
# each and every attribute in the class. Thus, in REAL code, you really need to do:
#

class A(object):
def __init__(self):
self.x = 10
def __getattribute__(self, attr):
if attr == 'x':
return object.__getattribute__(self, attr ) * 20
else:
return object.__getattribute__(self, attr )

#
# You can imagine the nightmare this becomes if you have to re-define many attributes.
# I've seen it and it is not pretty.
#

#
# Thus, in python, this sucks. The only way to work around it in python is to forget
# classes have attributes and always, always access attributes through a method, which,
# btw, cannot be named in the same way as the attribute.
# Thus, your code becomes sprinkled with:

a.x()
a.y()
a.z()

#
# And you attribute names probably become something like self._x instead.
#
#
# Python is not much of an improvement over Java's or C++'s OO, unlike Ruby.
#




Summary (whew it was long): opinions, personal taste, misunderstanding and misinformation. Is ruby community this desperate?

On your side, you mean, right? As Ruby community being desperate, there's no need. We have the best language around and we know it. Other people are just finding out about it, like Linux Journal:
http://www.linuxjournal.com/article/9368
(Scary, as I use about 80% of the applications mentioned there :)

Eventually, something will beat ruby, but it will probably take a while... particularly in the syntax department.


Ruby has good app: rails. Python community did not started smear campaigh agains Rails, but accepted the challenge and created *two* great rails-like frameworks: Django and TurboGears.

Ruby has *MUCH, MUCH* more than rails, as I've shown. Regarding Django and TurboGears, we'll see... After all, I'm still waiting on Zope to become popular :)

loell
December 25th, 2006, 11:24 AM
I'm still waiting on Zope to become popular :)

i'm sure many will agree that Zope does not need to be popular, unlike ROR.
it still lives on without any fuzz.

<mawe>
December 25th, 2006, 12:42 PM
For each python library you mention, I'll see if can show you an equivalent (or better) ruby library. My guess is that you'll need to find something pretty obscure, as most standard stuff is there (command-line parsing, vector/matrices, numpy, sdl, opengl, widget toolkits, etc)
Mhm, so what would be the equivalent for Python's numpy? Or VPython, matplotlib, ...

gga73
December 25th, 2006, 07:38 PM
Mhm, so what would be the equivalent for Python's numpy? Or VPython, matplotlib, ...

Sure...
Numpy = NArray. The web page of http://narray.rubyforge.org/ will probably give you pointers to other numerical stuff you might be interested in, too.
VPython = this is not a lib, but a combo of 3 libs. Probably several combos you can try. A simple one is NArray + FXRuby (see its opengl example with spheres, cubes, etc). For more complex 3d work, the stuff to beat will be Shattered Ruby, albeit that's probably aimed more at games (it is bindings to ogre3d with a MVC approach a la RoR).
matplotlib = any of RGPLOT, PLPLOT or OctaveIO , Ruby Matematica,
If you are interested in doing science with ruby, the best place of reference is sciruby at (with most libraries you'll find useful):
http://sciruby.codeforpeople.com/sr.cgi/InterestingProjects

ZuLuuuuuu
December 26th, 2006, 07:36 AM
gga73, thanks for such a detailed (post?) article. This will guide hesitating people which one to choose.

<mawe>
December 26th, 2006, 10:00 AM
Numpy = NArray
NArray is (as the author says) still experimental. I don't think it is equivalent to numpy right now.

VPython = this is not a lib, but a combo of 3 libs. Probably several combos you can try. A simple one is NArray + FXRuby (see its opengl example with spheres, cubes, etc).
:) ... nearly every language has OpenGl bindings. But I don't want to mess around with opengl basics. What makes VPython special is, it's easy to handle ("3D programming for ordinary mortals"). e.g. to create a scene with a sphere, I just have to write

from visual import *
sphere()
That's it. How easy is that with FXRuby?

If you are interested in doing science with ruby, the best place of reference is sciruby at (with most libraries you'll find useful)
I know this site. It's the reason why I choose Python for my projects :twisted:
When I last browsed through the "interesting projects", most of them were still alpha, and so IMO not ready to use. But this might have changed. I'll take a closer look at them.

Anyway, thanks for the info.

Regards, mawe

ghostdog74
December 26th, 2006, 10:54 AM
Python's syntax is very rigid. For example, you cannot do:

a = 20 if x == 20

how about this?


if x == 20: a = 20




which is relatively common construct found in C, Perl, Ruby, etc. You cannot also do things like do/while constructs, instead of while/do constructs. You don't have switch statements. The list goes on.


http://www.python.org/doc/faq/general.html#why-isn-t-there-a-switch-or-case-statement-in-python

A properly constructed while loop can do the same thing as do/while

http://www.faqts.com/knowledge_base/view.phtml/aid/17198




No, I didn't. Have you tried using it much in python? I have, and was extremely dissatisfied with it. Here's a place where tabulation comes to haunt you.
If you just eval a single command, there's nothing wrong with it.
However, if you try to start eval'ing code that is several lines long, with ifs/whiles/etc., it is a nightmare compared to Ruby's eval. You have to make damn sure your code is tabulated properly at all times. This more or less forces you to need to pass a tabulation variable or parameter to every function that creates code on the fly to later be evaled... to make sure the code actually *COMPILES*.
Not surprisingly, eval() is not used much in python code.
Now I consider the ability to eval code on the fly one of the main attractions of dynamic languages, and python just takes that feature and makes it very hard to use.


to eval several statements, they can be put into a function, and eval can execute that function
eg


>>> def func():
... x = 1
... x = x + 1
... y = 2
... y = y + 2
... return x,y
>>> eval("func")()
(2, 4)


exec() can also be used to execute multiple statements.



Yep, familiar with it and also with its distant cousin the regex module.
Problem is, they are not built-in.
Thus, every regex comparison in python usually is divided into 2 or 3 annoying steps (a 4th if you include the import too): create the regex, use it to compare it and find the match results. A typical regex code in python looks like:


import re
r = re.compile(r"^([a-z])", IGNORE_CASE )
m = r.match( string )
if m:
print m.group(1)




They are "built" into Python. Python ships with it. It is however not built into the interpreter.(IMO,it keeps the interpreter binary small) .It is not necessary to solve everything using regexp in Python. Even the abovecode example can be solved using simple string indexing and slicing plus others.
By the way, the above can be written


print re.compile(r"^([a-z])", re.I ).search(string).group(1)





a) Ruby's functions/methods can be invoked without parenthesis.

message("hello, this is an example in python")

message "hello, and this is in ruby"

b) Ruby supports blocks, python doesn't.
This is an actual ruby DSL (it is ruby code) I've developed for managing 3d renders:


render {
scene "hello.ma"
frames 1..9, 30, 20
overrides {
layer "beauty" {
antialias 3
}
}
}


so what is the advantage and disadvantage? In Python,you can define that block in a function.




d) Ruby's methods (and functions) support special characters in their names, like ?, !, etc.


class A
def has_data?
# do something here
end
end

a = A.new
if a.has_data?
end


what is the advantage of this?



e) Ruby makes it easy to open built-in classes and add methods. For example:


class String
def no_spaces
return ! include? ' '
end
end

puts 'This should have no spaces'.no_spaces


Compare that to Python, which still struggles with some of this:



def no_spaces(self):
if (' ' in self):
return False
return True

str.no_spaces = no_spaces

print('This should have no spaces'.no_spaces())
>> TypeError: can't set attributes of built-in/extension type 'str'


I don't know, but i would rather not meddle with in built classes like that unless I have
absolutely no choice.




Hell, no! Teach them ruby instead! They'll find it easier and will probably end up writing better code in the long run.


I would say teach them both. And let them decide themselves.




As for the opposite, I've already mentioned one library not available in python (Getopt/Declare).

please do not say that. At least there is
http://docs.python.org/lib/module-optparse.html



For comparison and to show you how poor python is, I'll try to do something similar in it:

[CODE]
class A:
def __init__(self):
self.x = 10

a = A()
a.x
10

#
# Now, here you see how python is already breaking encapsulation and does not
# have any idea of what private is. All your attributes are exposed publicly by default.
# This is DANGEROUS.
#
# Worse, in python you can do:
#


This is just instantiating a class. IMO, its not breaking encapsulation. Also, its public
To keep private,got to use __ (double underscore)



a.xx = 20

#
# And now your instance also has an xx attribute!!!
# So much for proper OO. This breaks COMPLETELY the whole concept of OO, which is
# to keep data private as much as possible within a class.
# A very simple typo in your code in Python can lead a function mis-behave, as you
# just create a new attribute in your instance!!!
#


why not? sometimes ppl just want to create empty classes and adding attributes as
they go along...




#
# Python is not much of an improvement over Java's or C++'s OO, unlike Ruby.
#


why not? at least i find coding the class constructor with multiple arguments in Python better than Java/C++




On your side, you mean, right? As Ruby community being desperate, there's no need. We have the best language around and we know it. Other people are just finding out about it, like Linux Journal:
http://www.linuxjournal.com/article/9368
(Scary, as I use about 80% of the applications mentioned there :)

Eventually, something will beat ruby, but it will probably take a while... particularly in the syntax department.


And the Python community will say they have the best language around.
There's no such thing as a BEST langugage. It all depends on the task at hand, and the coder's tastes.
There is no end to this if we keep comparing like this.

tseliot
December 26th, 2006, 03:04 PM
There's no such thing as a BEST langugage. It all depends on the task at hand, and the coder's tastes.
There is no end to this if we keep comparing like this.

Amen

gh0st
December 26th, 2006, 11:43 PM
Python isn't going anywhere I don't reckon. The community support is too strong. I think Ruby is getting a lot of press because Ruby On Rails was a breakthrough in rapid web development (I'm sure someone will correct me on that :-)) but now Python has Django and Turbogears. I am just getting started with Django but I have to say it's pretty impressive.

I haven't really tried Ruby, I have nothing bad to say about it, I'm sure it's great but I'm perfectly happy with Python and I think a lot of other people feel the same. That's why Python is here to stay IMO

ZuLuuuuuu
December 27th, 2006, 07:16 AM
There's no such thing as a BEST langugage. It all depends on the task at hand, and the coder's tastes.
There is no end to this if we keep comparing like this.

But I do think there are better languages than some ones. When anyone say a sentence like you say then I get suspicious about the language what he/she uses. This is because of a choice I made. ASP over PHP.

There were a lot of discussions about PHP vs ASP and people were always saying that the languages are equal. It depends on programmer to which one to choose. Some people were saying technical things but because I didn't understand them I relied on people who are saying it is useless to discuss that and the languages are equal. So I choose ASP and now very regretful about it.

Even for sending email or uploading things I depend on third party components which are non-free. PHP is always getting better while ASP is stuck what it is years ago. I cannot find some functions on ASP while it is in PHP (and no way to implement it but using again a third party non-free component). There are still people who say "both languages are fine, it depends on your taste which one to choose" and they are mostly ASP users. PHP users are aware that they have the better language. Like gga73 saying "Ruby users are aware that they have the best language". It is like deja-vu for me.

At that time ASP was most widely used language for web applications (I think that was the reason I choose it). It is like Python is widely used now isn't it? I think if a language is better, then it will become the widely used language. Like PHP become today.

Some things gga73 say are really depend on taste like there is no brackets on Python or it is restrict from the point of view of syntax. I really loved that there is no brackets in Python. Because I like writing programs this way:



Bla bla bla
{
Bla bla bla
}


Some people like this:



Bla bla bla
{
Bla bla bla
}


and some people this:



Bla bla bla {
Bla bla bla
}


If more than 1 programmer comes together and one like another syntax and other one the another, then which syntax will be choosen? A programmer should change his/her habit? But if the language is restrictive about that and forces the programmers to write it in one way than there will be no chaos.

So, I think the flamewars like this, are very useful :)

maxamillion
December 27th, 2006, 08:37 AM
I'm going to be "that other guy" and not argue which one is "better" because I have found that arguing what programming language is the "best" is just like shouting at a brick.... I prefer python because I like it, both languages are completely capable of performing tasks I read tutorials on each and made my choice and I recommend that to anyone else as well.

gga73
December 29th, 2006, 03:33 PM
how about this?


if x == 20: a = 20



Totally acceptable. Forgot about that one.



A properly constructed while loop can do the same thing as do/while


I'll go with no on this one. Functionality wise, they are identical, but in terms of readability they aren't. But I'll retract my comment of saying ruby does this better, because it doesn't.
The problem with a while 1: construct (or ruby's loop or begin/while equivalent) is that that constructs reads "infinite loop", which could easily be exited at several points, not a do/while construct that is usually just exited when the while construct is false.
It is only until you get to the break line (something that in real code can be several lines down) and you check there's no other break. that you realize you are in fact in a do/while construct.



...switch statements...


On this one, python is way off. Cascading if/thens and/or function dispatching are not a good replacement. Neither are the same in terms of ease of use and readability and, in the case of Ruby's case statement, they are not the same in functionality either.
I'll show you the beauty of Ruby on this one, because it really blew me away when I saw it:

Ruby:


case x
when 0, 1, 4, 9
# do something when x == 0, x == 1, x == 4 or x == 9
when 'hello', 'goodbye'
# do something when x == 'hello' or x == 'goodbye'
when /.*hel.*/
# do something when x =~ /.*hel.*/ (regex comparison)
when Person
# do something when x.is_a? Person ( class comparison )
else
# do something otherwise
end

The beauty of ruby's case construct is that:
a) There's no need for break statements, unlike C and the like. Each block is self-contained, until the next when/else/end keyword.
b) Multiple matches for a block are easily handled, by using commas in the when line.
c) Ruby uses the special === operator for comparisons in case statements. This operator by default tries to dispatch the comparison to the object's most logical comparison. So, if you compare against a regex, it compares using a regex match. If you compare against a Class name, you use is_a? while for strings or numbers, it compares using equality.
This allows a single case statement to compare against numbers, classes, strings, regex, or any other ruby object. While you hardly ever use something like what I just showed, the ability to have case statements that support regex and strings in a single comparison block is golden. And so are class comparisons within case statements.



to eval several statements, they can be put into a function, and eval can execute that function
eg

Sadly, neither a function nor exec helps much. You are still forced to know the context in what your code is to be evaled() and carry tabulation across.
For example, If you move the def() function you created to be created after a "class" statement, it won't get evaled properly unless you tabulate it correctly for that context. This is an additional burden, that gets worse if your functions that create the string to be evaluated create partial if/thens, functions, etc. for constructing longer evaluation routines.



They are "built" into Python. Python ships with it. It is however not built into the interpreter.(IMO,it keeps the interpreter binary small) .It is not necessary to solve everything using regexp in Python. Even the abovecode example can be solved using simple string indexing and slicing plus others.

That's somewhat of a silly argument. A binary regex engine does not add more than a few Kbs to the scripting language (at worst ) and the benefits in clarity of syntax are worth it.
The reason why python does not have a regex engine built-in is, imo, mostly historic due to pythonists (Guido?) not wanting to borrow *anything* from perl to distinguish themselves from it and from a culture they looked down on.




print re.compile(r"^([a-z])", re.I ).search(string).group(1)


Kudos for the try. I'll buy it. Don't find it particularly readable, but I'll buy it. So... is there any way you can run that as a one liner with python?


so what is the advantage and disadvantage? In Python,you can define that block in a function.

Okay, I'll show some sample code to create a dsl:

Ruby:

#!/usr/bin/env ruby

#
# The ugly "parser" bits
#
class Options
def initialize(&block)
@args = {}
instance_eval(&block) if block_given?
end

def method_missing(x, *args)
if args.size == 0
return @args[x]
else
@args[x] = args.size == 1 ? args[0] : args
end
end
end

class Render < Options
def options(&block)
@args[:options] = Options.new(&block)
end

def hello(x)
puts x
end
end

def render(&block)
Render.new(&block)
end

#
# the real DSL now (what the user sees)
#
a = render {
p 'xx'
hello 'hoo'
tryme 'help'
frames 1, 4, 5

options {
code 'this in options'
}
}

# Pretty-print the instance of the class we created
require 'pp'
pp a


The beauty of this is that in a few lines I created a small pseudo language for describing attributes, and these attributes automatically get fed into classes, thru instance_eval().
In this case, I ran the pseudo-language within the same file, but usually you place and load that from another file and you just eval the code.


what is the advantage of this?

Personally, I think it helps readability, particularly in a dsl context. Albeit subtly:

Ruby:


if female?
puts 'kiss in the cheek'
else
puts 'hand shake'
end

Python:


if a.female():
print "kiss in the cheek"
else:
print "hand shake"

Another benefit is you can easily distinguish in methods those that check conditions and those that don't.

irb> String.methods.grep /\?/
[ ... only methods that check conditions... ]

python> dir(str)
[ ... all methods together...which ones check conditions or return
boolean values? ]



I don't know, but i would rather not meddle with in built classes like that unless I have
absolutely no choice.


This is not as bad as a python guy would make you think.
In the context of introspection, which was the comparison being made, this can be very useful in debugging.
For keeping changes more local, I already showed ruby supports the << instance syntax to add methods just to instances of a class, not globally.
If you care for safety, another approach can also be using a module like:
http://blade.nagaokaut.ac.jp/~sinara/ruby/import-module/import-module-0.82/doc/README.html
This allows any changes to remain self-contained within a block, with a minor speed penalty.
Thus, you can write:

Ruby:


require 'import-module'

module Unsafe
def no_spaces?
not self.include? ' '
end
end

String.import_module( Unsafe ) do
# this will report false
puts "text has spaces".no_spaces?
end # no_spaces? is gone from string here

# this will fail...
puts "text has spaces".no_spaces?


As usual, Ruby shows its flexibility and power.


please do not say that. At least there is optparse

I'll probably keep saying it cause it is true. Optparse is hardly a good replacement, particularly in its python implementation.
BTW, Ruby ships with the same optparse thing in its std library, albeit it has a slightly more elegant syntax, due to the use of blocks.
However, this library is NOT the same as Getopt/Declare. Not by a long shot.

Compare the syntax of ruby's getopt-declare:

Ruby:


args = Getopt::Declare.new(<<'EOF')
-q[uiet] don't print status messages to stdout
-f[ile] <file:of> write report to file
EOF

vs. Python's optparse:


parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")

(options, args) = parser.parse_args()

The more flags and callbacks you have, the ugliest OptionParser becomes.
The beauty of Getopt/Declare is that it uses a humanly readable help syntax to define options.
This is brilliant idea and one of the greatest contributions of the Perl community.


This is just instantiating a class. IMO, its not breaking encapsulation. Also, its public
To keep private,got to use __ (double underscore)

I can see how you as a python guy see it as just instancing a class.
It breaks encapsulation because it exposes an internal attribute of the class outside of it by *default*. Sure, the __ syntax works around it ( I mentioned that ), but at the penalty of making your code inside class methods much less readable:

Python:

def do_something( self ):
return (self.__x + self.__hello) / self.__sum

vs. Ruby:


def do_something
(@x + @hello) / @sum
end



Also, as another problem regarding attribute access in python, is that if you have a method in a class called x() and you incorrectly access it as an attribute, like:

Python:


b = a.x

in python b ends up not with the value of x but with a:

<bound method A.x of <__main__.A instance at 0x2b6e670c3f38>>
(Basically, a pointer to the member function)

While this is cool for functional programming, again a simple typo can lead to a bug (albeit this one will probably end up throwing some stack trace later on). Thus, when accessing attributes in python you have 2 or 3 things to watch out for.

Ruby solves the above issue by doing:

b = a.method( :x )

so there's never any confusion when you want to do functional programming than when you want to access an attribute. Again, I find this much smarter and much safer than python's approach.


why not? sometimes ppl just want to create empty classes and adding attributes as
they go along...

Because it is not good OO behavior to do that. You are exposing your class internals to the outside and you are allowing other people to easily misuse your library and/or change the internal contents of the class. A bug like that can easily be hard to track, as it is NOT a bug that will throw a stack trace easily.
Sure, in *some* instances you do want that. But if you *do* want to have attributes created on the fly, you should write code to allow that in your class. See the example I posted with Ruby's DSL. I allow just that, but it is NOT the default behavior in the language. I think this is a good thing.
Ruby also ships with OpenStruct in its library to easily allow that too, btw. Example:


require 'ostruct'

a = OpenStruct.new
a.x = 20
p a.x



why not? at least i find coding the class constructor with multiple arguments in Python better than Java/C++

Really? The class constructor does not change that much between those languages. Python and Ruby do bring the *huge* benefit of a dynamic language (not needing to define the types of variables or init them and invoking classes is easier, no compilation, etc) and it avoids the many gotchas present in C++ and, a tad less in Java. They also are less verbose.
But I don't agree Python's constructors (or its OO) are that much of an improvement in readability. Compare just a class based on integers (written in short form on all languages):

C++:


class A
{
private:
int _x, _y;
public:
A( int x, int y ) : x( _x ), y( _y ) { }
int x() { return _x; }
void x( int xx ) { _x = xx; }
int y() { return _y; }
void y( int xx ) { _y = xx; }
};

Java (not a language I know well, thou):


class A {
private int _x;
private int _y;
public A(int x, int y) {
_x = x; _y = y;
}
public int getX() { return _x; }
public int getY() { return _y; }
public void setX( int x ) { _x = x; }
public void setY( int y ) { _y = y; }
};


Python:


class A:
def __init__( self, x, y ):
self.__x = x: self.__y = y
def x( self, xx ): self.__x = xx
def x( self ): return self.__x
def y( self, yy ): self.__y = yy
def y( self ): return self.__y


Ruby:

class A
attr_accessor :x, :y
def initialize( x, y )
@x = x; @y = y
end
end


or even simpler-- Ruby, again:


Struct.new ( "A", :x, :y )
A = Struct::A


The four (five?) of them do the same (well, the python and ruby ones do not really check the variables passed are indeed integers, albeit they could), but I do find the ruby approach much more readable and the accessors work just like attributes, unlike all the others. Looking at those languages from top to bottom there's almost a clear evolution in syntax.

For completeness, and to make ruby look worse, here's the ruby version with type-safety, too (validating the values passed are indeed integers at runtime):


class A
attr_reader :x, :y
def initialize( x, y )
@x = x.to_int; @y = y.to_int
end
def x=( x ); @x = x.to_int; end
def y=( y ); @y = y.to_int; end
end



And the Python community will say they have the best language around.

Sure. It just gets harder to believe it if you know Ruby.
Language comparisons are not silly. They are truly useful when you show equivalent code and defend why an approach is better or not.
Even when there's no agreement, you still learn something about writing code.

pmasiar
December 29th, 2006, 05:57 PM
(discussion about regex engine being standard external library in python vs. build as part of language syntax as in ruby/perl)



A binary regex engine does not add more than a few Kbs to the scripting language (at worst ) and the benefits in clarity of syntax are worth it.
The reason why python does not have a regex engine built-in is, imo, mostly historic due to pythonists (Guido?) not wanting to borrow *anything* from perl to distinguish themselves from it and from a culture they looked down on.
...

So... is there any way you can run that as a one liner with python?

Exactly. Python *culture* is not optimized for one-liner regexes using by experts to show-off superiority and confuse beginners. You have to write full loop with all three lines of python code to do same thing - and we like it that way. *Clever code* has negative connotation in python - code is good if is easy to understand.

Python has basic string methods (split, strip, startswith, endswith, find, rfind), which are "part of language" and satisfy at least 80% of standard usage (and cover 100% of beginner needs), without forcing beginner to learn confusing regexes to solve basic problems. When need arises, re is part of standard library, ready to be used, but not before.

Guido was concerned not about saving couple KB of memory, but about adding complexity to language unnecessary for 80% of applications.

Let me tell you that so far string methods was enough for my apps. :-) And IMHO code is still simple to read and understand.

If you want to understand python, start python shell and type 'import this'. Python strives simplicity, not complexity.

gh0st
December 30th, 2006, 02:22 PM
I'm going to be "that other guy" and not argue which one is "better" because I have found that arguing what programming language is the "best" is just like shouting at a brick.... I prefer python because I like it, both languages are completely capable of performing tasks I read tutorials on each and made my choice and I recommend that to anyone else as well.

That's very sound advice. Just cos something is better for one person doesn't mean it's best for everyone. Choice is good.

Love the "shouting at a brick" analogy by the way :) :)

gga73
December 30th, 2006, 02:48 PM
Python has basic string methods (split, strip, startswith, endswith, find, rfind), which are "part of language" and satisfy at least 80% of standard usage (and cover 100% of beginner needs),

I'll answer this simply. Ruby, again, thru irb (interactive ruby console):

irb> String.ancestors
> [String, Enumerable, Comparable, Object, Kernel ]

irb>(String.instance_methods - Enumerable.instance_methods - Object.instance_methods).sort
["%", "*", "+", "<", "<<", "<=", "<=>", ">", ">=", "[]", "[]=", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "concat", "count", "crypt", "delete", "delete!", "downcase", "downcase!", "dump", "each", "each_byte", "each_line", "empty?", "gsub", "gsub!", "hex", "index", "insert", "intern", "length", "ljust", "lstrip", "lstrip!", "match", "next", "next!", "oct", "replace", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "size", "slice", "slice!", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "to_f", "to_i", "to_str", "to_sym", "tr", "tr!", "tr_s", "tr_s!", "unpack", "upcase", "upcase!", "upto"]

irb> a = "This is a test for slicing"
irb> a[0,5]
=> "This "
irb> a[-5,5]
=> "icing"

So you see... in Ruby, unlike Perl, having regex built-in does not mean you don't have those methods you like available to you. You do (and more).
Once you have a tougher problem to solve than those methods can't solve or can't solve efficiently, you can proceed to use a regex.
The advantage with ruby is that once you DO learn regular expressions, they're always there at your fingertips (like Perl) and that many of those search methods will accept both normal strings and regexps.

For help on any method, from the shell:

> ri 'String.split'
....Long help....

If you have wirble installed, you can also do the same from irb.

As a joke...

irb> Ruby.ancestors
[ Python, Perl, Smalltalk ]

I think I mentioned this, right?



If you want to understand python, start python shell and type 'import this'. Python strives simplicity, not complexity.

The python haiku is just a good programming haiku. You won't get complaints about it.

But... if you want to learn Ruby, play with it first a little bit. You don't even need to install it! :)

http://tryruby.hobix.com/

Might be a tad slow, depending on your connection (and people using it), thou.
And you can't load external modules or do unsafe things, for obvious reasons.

eukhost.com
January 1st, 2007, 12:43 PM
I would say Python, because it's a very clear language and it often reads like pseudocode. Its clean, simple and elegant and can do procedural or object-oriented.

Ruby is abother good choice and with either one you'd have a good foundation for both system level scripting and web development.

Burgresso
January 1st, 2007, 10:09 PM
Python rules.

tc101
February 6th, 2007, 07:45 PM
I've read over this whole discussion. I have learned a lot but am still just as confused as when I started.

I'm a retired programmer from the Microsoft world and want to learn something new for my new life as a computer hobbiest.

Ruby has the new and cool factor, but still in the poll, people voted for Python over Ruby by a 2:1 ratio. That seems significant, although maybe it is just because Python has been around longer and more people have more experience with it.

At this point I am leaning towards Python because of the results of the poll, and because it has more books and web sites and tools available. I am not decided for sure yet. I will spend a few more days reading about this.

jblebrun
February 6th, 2007, 11:17 PM
Side note: you don't have to compile a re in python. You can just write



if re.search('^abc',mystring): print mystring


Still a little more verbose than the ruby construct, but I would call it more readable. Python code is definitely the most self-documenting code I've seen, hands-down.

I like both Python and Ruby. They both have their quirks and pluses, and both are enjoyable languages to use. Python pisses me off a lot. For example, the other day I wanted to re-write the way a time object represented itself as a string. But too bad, I wasn't allowed to overload the __str__ operator. I had to subclass. Booo. Of course, this let to further problems with I threw in timedelta... MyTimeSubClass + TimeDelta results in a regular time object. So I also had to add in type casting in my subclass. WAY to much crap just so I could overload a string function. It's quite possible that I just approach this in the wrong way, but I thought about it for a while, and consulted with my Python guru friend, and that was the best result that I could come up with.

I'm going to hypothesize that another reason that people gravitate towards Python is that from a "clean-slate" point of view, Python is more readable than Ruby. What I mean is that someone who doesn't know anything about either language is more likely to understand python code the first time seeing it. However, I don't find this a terribly important feature of a language. If you're going to learn a language well enough to do any real work in it, you'll quickly become intimate with the syntax. Ruby is still very easy to understand.

And of course, you have people that will point out that Ruby is very lisp-like, even moreso than Python, and this will cause a certain subset of people to run screaming. Frankly, I find that quality pretty exciting. I've done a bit of coding in Scheme, and while I found it fun and interesting, the syntax was too mind-numbing to make me ever consider approach a large project. For whatever reason, Lisp-like syntax is just not something that sits well with me. It is conceptually very kick-*** though!

I'm off to play with Ruby some more. Bye!

jblebrun
February 6th, 2007, 11:29 PM
Oh, also, if you want an improvement over python's crappy command-line interpreter, check out the ipython packages.

LordHunter317
February 7th, 2007, 03:28 AM
but both the Java and .Net virtual machines are huge memory and CPU hogs.Not especailly.


By contrast, the Python interpreter seems downright small and efficient, not using all that much memory. Unless you have long-lived applications that allocated and dump a lot of resources of varying sizes. Python's pretty poor about avoiding fragmentation.


Thus, in my experience, Python apps launch quicker, and are generally snappier than equivalent Java or C# apps.Or until you need lots of threads, where the interpreter ends up biting you in the *** hard.


Python's lack of built-in regex makes it pretty painful to use for sysadmin tasks or one-liners, unlike ruby.Well that's just plain false.


Over the years, I have learned that multi-inheritance is unneeded, and that a model based on single inheritance with mix-ins is a better approach.Mixins are superior than trying to force MI into a hole where it doesn't belong. But they have a large cost associated with them. MI is a prefectly fine approach, when used correctly and judiciously. The valid usages are just quite narrow.


Python makes its interpreter also be its interactive terminal. Again, this is a mistake, as it prevents users from easily configuring it or expanding on it (this forced python users to eventually create their own interactive terminals).This is true of virtually all interpreters and is just plain nonsense, moreover it's hypocritical with this:
In comparison, ruby's irb is much less useful out of the box, but much more productive after a year of use (well, with wirble, you now get it more productive after 5 mins now . What you meant to say is that the interpreter's interactive features are poor. That's a world of difference.


This makes Ruby's OO very similar to Smalltalk's, with mix-ins being similar to Java's.Java doesn't have mixins.



a = 20 if x == 20
which is relatively common construct found in C, Perl, Ruby, etc.Drop C from that list. It's also a major syntax incosistency and Perl and Ruby are both incredibly ****witted for allowing it. The orthogonality loss always hurts more than a dubious gain in readability. Always.


Yep, familiar with it and also with its distant cousin the regex module.
Problem is, they are not built-in.Yes, they are. Lack of regex operator doesn't mean not built-in, and it's insulting to even forward that argument.


a) Ruby's functions/methods can be invoked without parenthesis.Which is again, beyond ****witted. Loss of orthogonality is always bad. Always to be avoided.


Most of the features of multiple-inheritance can often be solved with mix-ins, and in the very weird case it can't, you can implement multiple inheritance with dispatching.Manual dispatching isn't the same thing, because it's what the language is supposed to be providing for you. It's not remotely close. Again, insulting to even forward such an arugment.



# And now your instance also has an xx attribute!!!
# So much for proper OO. This breaks COMPLETELY the whole concept of OO, which is
# to keep data private as much as possible within a class.
# A very simple typo in your code in Python can lead a function mis-behave, as you
# just create a new attribute in your instance!!!
#Nope, sorry, you do not understand OO if you believe that's what it's about. Protected access is one small implementation detail on what OOP is actually about.


On this one, python is way off. Cascading if/thens and/or function dispatching are not a good replacement.Function dispatching is always superior when you can do it because it's almost always faster and more compact. That is what 'virtual' and friends get you in OOP. A switch -> extensible lookup + pointer dereference.


A binary regex engine does not add more than a few Kbs to the scripting languageFactually wrong.


. You are exposing your class internals to the outside and you are allowing other people to easily misuse your library and/or change the internal contents of the class.You realize how hypocritical you're being by dissing this and then lauding Ruby's reflection and extension capabilites, right? Aruging about protected scope in a dynamically-typed langauge is ultimately very, very foolish. There's a reason why some essentially don't bother, like Javascript. Protection in that language is a side-effect of closure behavior and nothing else.

You have some valid comments on some the readability differences (though I find both unreadable trash for different reasons), and perhaps some of the library differences. But your commentary on things OOP is quite off. Preference for readability over orthogonality is something I find personally disturbing as well. Some people like it, I'm pretty throughly convinced the readability gains don't exist because there's just too much ambiguity when you have lots of ways of doing things.

lnostdal
February 7th, 2007, 06:49 AM
I've read over this whole discussion. I have learned a lot but am still just as confused as when I started.

Confusion is much better than lazy comfort leading to no future progress. Without having any initial confusion and discomfort before eventually reaching your goal, you can be sure you've learned nothing truly new. So you're doing great. :)

..some babblings follow..

Do not judge something like this by number of fans or users. This is especially true since you will be doing this as a hobby and for your own enjoyment. What matters in the long run is what qualities you want in your language. The language(#1) has to inspire you. You are the one who will be doing the coding once you get over the initial thresholds. Thresholds vary. Sometimes a lot. But they do not matter much once you're past them as they are all small compared to the time you will spend on actual coding. This is why research, thus current confusion - are good things. It's well spent time.

You'll find enough people using the language you pick anyway. You'll find enough projects you can be a part of if you do not want to start your own project. Heck, I'm using Common Lisp and there's almost "no one" using that - right? But I haven't been more sure, inspired and energized about anything like this in a long, long time. I think last time was when I discovered Linux - or when I began trying it out a bit around 1998-9 and made a total switch in 2001. I'm still excited about Linux of course. Lisp has only added to this exponentially. The number of Linux-users wasn't that great back then, but it didn't matter. The users that existed where the ones who truly understood, had made a conscious choice and where genuinely interested. It was the same with Lisp. Probably the same with Ruby and other languages too.

I remember people thinking I was focusing on the wrong things. This happened both when I went for Linux - and when I went for Lisp. They though I was "shallow", and that I was just following what the "fan bois" where following. That I was following something based on trivial or "non-real" issues in what already existed(#2). That I had a naive focus on the "coolness" of it. That I wasn't thinking practically or rationally and other things. These things have been mentioned for me many-many times. They still are sometimes - but more seldom every day. I can usually shut their boring, non-visionary, imagination-lacking, lazy - mouths now. Anyhow, I did really see things in a "deep" way, or at least I had a good enough idea(#3) of what these people where trying to create and what they where missing in what was already out there - and that I also missed these things. I saw genuine problems that could not be solved while going in my current direction .. ever. Something was fundamentally broken and un-fixable. I had to do some research to discover these things though, then I had to do some more to confirm them as "real" and that they where, for what I could see - on the right track towards proper solutions that would last and didn't bring other worse problems with them.

A question I've been wondering about though; what reasons do you have for wanting to look for something else than .NET/ASP in the first place? What do you lack? Maybe something to figure out then keep in mind while exploring. (sorry if you've already mentioned this in a post back somewhere)

..anyhow, Linux and Lisp (with C) has turned out as great choices for me - but they do not have to be for you though, there are other alternatives out there .. so more babblings about research and such follow..

You'll want to spend some time trying to get as much background info about each choice as possible. While the "fan bois" might give some hints and tasters showing some of a language's greatness, try getting or confirming as much info from good quality sources specialized in their own field as possible. Try to understand what things will imply in a larger or different context, both design- and performance-wise. The most subtle differences can often have major consequences. Do some research. Compare and understand compromises - some of them are not compromises even if they seem to be on the surface. Map out as much as possible. There is enough resources out there to do this and be reasonably sure you've chosen the right language when done. Also spend some weeks trying out each language. Confirm that you are reading the latest info about a language, and that it is from a "safe" source. This forum is not it; you will not find confirming or "safe" info here. Certainly not via a vote(#4). You'll only find leads that you've got to pick up on and follow then confirm yourself.


#1: ..and the language is more important than the libraries if you are to enjoy what you are doing -- otherwise you might as well pick Java.. :) ..there is one exception here and that is C, not because it lacks libraries though .. it is almost required knowledge because the Linux-kernel and quite a bit of surrounding software is written in it -- but that's just about the only reason to bother with it .. it can be a rather big "only reason" though - at least in some cases.. i think you'll figure this out

#2: c'mooon people .. bring out the turing-machine argument - i need a good laugh

#3: ..ofter big problems describing these things though; still do..

#4: ..do note that i'm no ruby fan; i mean - the standing of the vote does not bother me -- i do not know enough about the difference between python and ruby to care .. just don't let something like this be what decides

pmasiar
February 7th, 2007, 04:23 PM
Oh, also, if you want an improvement over python's crappy command-line interpreter, check out the ipython packages.

I agree that ipython is better than plain python command shell - but I vehemently disagree with the plain default shell being "crappy". Plain Python shell is IMHO one of the best features Python has, and is more than good enough for beginners. I challenge you to show me another mainstream language with better standard shell than Python.

Noobz may think that if Python has "crappy" shell, whole language is crappy - and nothing is farther from truth, and I know you know it :-) so let's put the record straight.

yaaarrrgg
February 7th, 2007, 04:35 PM
I'm leaning towards Ruby slightly, although there still a lot about the language that bothers me. Python and Ruby are both in a hype stage (like Java was ten years ago)... and I imagine in ten years from now they will be hated as much as any other language. :)

The "easiness" and "coolness" factor of a language is a double-edged sword, IMO. What ever is most loved language now will probably be the more hated of the two in the future :)

Certainly, the romance with Python/Ruby will be dead when there are 100k's lines of buggy legacy code written in this, that needs to be touched on each new release of the language. Then there will be another language invented, if not for the sole purpose as an excuse to throw away all the Python/Ruby code and to start from scratch :)

IMO, I don't think there's truly a need for either of these hyped languages. It would be better to just write better libraries, tools, or alternate syntaxes for the ones already designed. Seems a bit pointless to reinvent the wheel only to discover different problems with it ...

I'm puzzled what thing that Python/Ruby can do that, for example, LISP hasn't already done... except maybe using less parans in syntax. Why not then just remove the parans (use tab-based scoping, for example) rather than reinventing the wheel? :confused: Then again maybe LISP needs a more macho sounding name, like BOA. :)

lnostdal
February 7th, 2007, 09:25 PM
I'm puzzled what thing that Python/Ruby can do that, for example, LISP hasn't already done... except maybe using less parans in syntax. Why not then just remove the parans (use tab-based scoping, for example) rather than reinventing the wheel? :confused: Then again maybe LISP needs a more macho sounding name, like BOA. :)

While at one level the parens isn't really there(#1), they must be there to support things like macros which is one of the most powerful features. They did add non-paren syntax to Lisp once (m-exps#2) but no one used it. It turned out that it was not interesting because the parens was not a problem but a positive feature.

#1: I do not notice them at all. In the same way I do not notice the syntax in C either. To me, the examples here look exactly the same while searching for structure with my eyes: http://ubuntuforums.org/showpost.php?p=2102814&postcount=28 .. The computer however is having a harder time searching for structure in C-based syntax (at least meta programming-wise, or whatever). Uniform syntax like you find Lisp is much easier for the computer to find structure in, therefore Lisp has such good data-is-code-code-is-data, meta and macro-programming features. Just see how hard meta-stuff is in C in this simple example: http://lists.warhead.org.uk/pipermail/iwe/2005-July/000130.html .. it will be exponentially harder when doing just a bit more complex meta-stuff.

#2: http://en.wikipedia.org/wiki/M-expression

yaaarrrgg
February 7th, 2007, 10:15 PM
While at one level the parens isn't really there(#1), they must be there to support things like macros which is one of the most powerful features. They did add non-paren syntax to Lisp once (m-exps#2) but no one used it. It turned out that it was not interesting because the parens was not a problem but a positive feature.

yeah... I don't think the parantheses can be removed completely, but they might be made optional (in some cases).

Looks like there's already an implementation of the idea... but I hadn't had time to look at it in detail:

http://www.lispin.org/

Other than that, a simple pre-processor script would do most of this...

lnostdal
February 7th, 2007, 11:14 PM
Looks like there's already an implementation of the idea... but I hadn't had time to look at it in detail:

http://www.lispin.org/


No Lisper wants this, and no Lisper will use this. Lisp is _already_ indented to emphasize visual structure and has _excellent_ readability. The problem just - isn't - there. It has been proven many times, first with m-exps and many-many times over the years with proposals like these. It is not an improvement. It is a step backwards. No Lisper will use this -- ever.

..kinda makes you wonder why? good(#1).. :)

Do you remember the reaction you had the first time you looked at C code? I do, and it was the same first time I looked at Lisp-code. The ( and ) is part of Lisp in the same way that { } ; , ( and ) is part of C.

Every nth day some Lisp-newbie(#2) jumps into comp.lang.lisp and posts something about these things. It's always the same; the poster is ridiculed and/or a flame-war starts and it always turns out to be based on the same misunderstanding that many of the Lispers _themselves_ once had (me too). This is one of the first misunderstandings with Lisp, and one of the first thresholds one meet when learning Lisp. No exception. The trick is to get over it as soon as possible. When you do you'll eventually start seeing why they are needed and why that uniform(#3) syntax is an _extremely_ good thing.



Other than that, a simple pre-processor script would do most of this...

Trust me on this; it would definitively not - and it would not be simple.


#1: If you're curious - take a look at what others have said while learning/discovering Lisp (yes, lisp with parens .. lol :)):
http://wiki.alu.org/The_Road_to_Lisp_Survey
http://wiki.alu.org/Kenny's_RtLS_Top-Ten
http://wiki.alu.org/RtL_Highlight_Film

#2: Actually, some intermediates or experts from other language-backgrounds are especially thick headed when it comes to this.

#3: Maybe "uniform" is a poor word for this .. http://en.wikipedia.org/wiki/Homoiconicity is probably more correct

tc101
February 8th, 2007, 06:03 AM
A question I've been wondering about though; what reasons do you have for wanting to look for something else than .NET/ASP in the first place?

I am fascinated by the whole open source community and want to be a part of it. .NET/ASP are part of a different world. If I needed to keep working to make money, I know I could make more money with .NET/ASP, but I don't have to do that any more and want to explore other things.

MatthewMetzger
February 12th, 2007, 07:38 AM
I am fascinated by the whole open source community and want to be a part of it. .NET/ASP are part of a different world. If I needed to keep working to make money, I know I could make more money with .NET/ASP, but I don't have to do that any more and want to explore other things.

I'm impressed and inspired by your attitude. Thanks for being an example of someone who values life-long learning.

kripkenstein
February 12th, 2007, 07:13 PM
Regarding the issue of "self." that appears in Python code (mentioned in this discussion). In general Python code is shorter than other languages (see the benchmarks on Debian's language shootout site; I can find the link if anyone wants it). "self." is a rare exception, in that it makes Python code longer than the same code in another language. But actually it makes a lot of sense.

Consider C++. If you have a member variable 'name', and have


myClass::myClass(string name)
{
name = name;
};

That won't work - name can't be used in two different ways with the same syntax. So, instead, people write things like


myClass::myClass(string init_name)
{
name = init_name;
};

which basically solves the problem - for this instance. But the issue is larger. It occurs whenever there is the possibility of confusing a member variable with a parameter to a member function, and that occurs quite often, actually.

Really, the safest thing to do is to require different syntax for member variables and parameters. Parameters probably shouldn't change (since you want to keep functions the same as always; not every function is in a class), so changing the syntax for member variables makes some sense. Hence "self.name" in Python.

Yes, it does make the code slightly longer. But it goes well with the general advantage of Python code - other people can read your code and understand it. When you see "self.", you know it's a member variable; when you don't, it isn't. Much easier for people seeing the code for the first time to jump right in.

jblebrun
February 12th, 2007, 09:53 PM
Regarding the issue of "self." that appears in Python code (mentioned in this discussion). In general Python code is shorter than other languages (see the benchmarks on Debian's language shootout site; I can find the link if anyone wants it). "self." is a rare exception, in that it makes Python code longer than the same code in another language. But actually it makes a lot of sense.

Consider C++. If you have a member variable 'name', and have


myClass::myClass(string name)
{
name = name;
};

That won't work - name can't be used in two different ways with the same syntax. So, instead, people write things like


myClass::myClass(string init_name)
{
name = init_name;
};

which basically solves the problem - for this instance. But the issue is larger. It occurs whenever there is the possibility of confusing a member variable with a parameter to a member function, and that occurs quite often, actually.

Really, the safest thing to do is to require different syntax for member variables and parameters. Parameters probably shouldn't change (since you want to keep functions the same as always; not every function is in a class), so changing the syntax for member variables makes some sense. Hence "self.name" in Python.

Yes, it does make the code slightly longer. But it goes well with the general advantage of Python code - other people can read your code and understand it. When you see "self.", you know it's a member variable; when you don't, it isn't. Much easier for people seeing the code for the first time to jump right in.

Another thing to remember is that you don't have to use the word "self" in your own code. This is equally valid:



class MyClass():
def function(s, in):
s.value=in


as is this:



class MyClass():
def function(reference_to_currently_executing_instance _of_this_class, in):
reference_to_current_executing_instance_of_this_cl ass.value=in


Using "self" for this placeholder is a pretty standard convention, and changing it could arguably hinder the readability of your code, but I do know some people who use "s." instead of "self." (Incidentally, I don't know anyone who uses "reference_to_current_executing_instance_of_this_cl ass" instead of "self" ;-) )

unipal
February 13th, 2007, 12:19 AM
Hello everybody,

check this out: C++ vs Java vs Python vs Ruby : a first impression

http://www.dmh2000.com/cjpr/index.shtml

my two cents

lnostdal
February 13th, 2007, 04:41 AM
Hello everybody,

check this out: C++ vs Java vs Python vs Ruby : a first impression

http://www.dmh2000.com/cjpr/index.shtml

my two cents

i haven't read the whole article but did notice one thing:

interpreted vs. compiled is a big productivity win for Python/Ruby

*shrug* .. python/ruby could just as well be compiled without losing the productivity the author probably thinks of here .. the productivity win is because you can make changes without having to stop the program, recompile, then start it again, then bring it back to the same state you had it in to debug/see results .. adding compilation does not remove these features whatsoever ..

lisp has had this for for years.. as i type this..

(defun hello () (write-line "Hello World"))
into the REPL and press enter (or press a shortcut-key to trigger re-evaluation/compilation while working on code in a file) ..it immediately compiles the code in `hello' to native machine code and "binds" it to the symbol/name `hello'.. i can now type..

(defun hello () (write-line "Hello again, World!"))
..and it will compile the code, then re-bind the compiled result to `hello' at run-time .. ..

here you can see it actually happing while depending stuff is running in a background thread:



AMC> (defun hello () (write-line "Hello World!"))
AMC> (hello)
Hello World!
AMC> (defparameter *background-thread*
(withThread
(loop (hello) (sleep 5))))
Hello World!
Hello World!
Hello World!
AMC> (defun hello () (write-line "Hello again, World!"))
style-warning: redefining hello in DEFUN
Hello again, World!
Hello again, World!
Hello again, World!


ok, well enough of that ..ruby/python might eventually get a compiler too..

LordHunter317
February 13th, 2007, 06:23 AM
Hello everybody,

check this out: C++ vs Java vs Python vs Ruby : a first impression

http://www.dmh2000.com/cjpr/index.shtml

my two centsOne might suggest since the man can't write a single line of correct C++ code, he ought to be ignored.


ok, well enough of that ..ruby/python might eventually get a compiler too..It already has one and has had one for sometime.

lnostdal
February 13th, 2007, 06:46 AM
It already has one and has had one for sometime.

ah, yes .. python compiles to some byte-code, doesn't it

anyways.. point was that having stuff compiled, even to native code to emphasise that there does not have to be a clear productivity / run-time trade-off - doesn't have to remove the productivity gains normally associated with working with interpreted languages

i've often heard people say "it's so dynamic and flexible because it is interpreted .. you don't get that in compiled languages" .. and it's just wrong -- that is; it doesn't _have_ to be that way :)

pmasiar
February 13th, 2007, 02:18 PM
i've often heard people say "it's so dynamic and flexible because it is interpreted .. you don't get that in compiled languages" .. and it's just wrong -- that is; it doesn't _have_ to be that way :)

People often confuse dynamic typing/late binding with being interpreted.

Python is dynamically typed AND compiled (into bytecode). AND can be compiled into executable, if so desired.

Old BASIC was interpreted without being dynamically typed.

Yeah, lot of noobz have strong opinions about issues they have no clue - only heard or read on some blog, and just repeat what they misunderstood :-)

jordan_mega_gamer
February 18th, 2007, 04:08 AM
Hi! I'm new here (well, I've been lurking for about two weeks, but...) and I've been looking for a programming language to study. I've pretty much narrowed it down to Python and Ruby, but it's hard for me to choose between the two. Can somebody tell me which one would be better for making games? I know, C++ is best, but I tried to learn that once and just didn't get too far. :mad: I don't expect amazing performance, really - I just want something to mess with until I can start learning C++ in college. So far I'm leaning towards Ruby, because there are too many different options for 3d programming in Python. (One site had 73 listed!) In contrast, for Ruby there's only one, Shattered Ruby, which I hope will be simpler. I'm still not sure though. :confused: Do you have any advice?

Mirrorball
February 18th, 2007, 04:25 AM
I think that Python having more libraries is an advantage, not a problem. Python is more popular too. Ruby's recent popularity is mostly due to Ruby on Rails, which is a framework for web development. All the benchmarks I've seen show that Python is faster than Ruby. Ruby users like this language because they say it reads like a natural language, but I don't see why you would want that. Natural languages are not precise, often ambiguous, often unclear. They are good for poetry, but I'm writing a program, not a poem! Python on the other hand is a favorite because it's clean, explicit and simple. The structure is rigid, the indentation has to be correct. It helps you think clearly and precisely. That's just my opinion. I really like tidy Python code.

jordan_mega_gamer
February 18th, 2007, 09:42 PM
Well, thank you for the advice. I think I'll probably have to try both of them and see for myself... but I'm going to test Ruby first. One of the other things that caught my eye was the ability to write a DSL in Ruby. I could be wrong, but doesn't that mean I could (for example) write a game editor, with a custom scripting language as the DSL? That would be a key feature for me because I've always supports games that are moddable.

Wait... I just looked and Python can make DSLs too... Hard to choose... :confused:

lnostdal
February 19th, 2007, 12:25 AM
To add further confusion I'll add Lisp to the set of languages suitable for creating DSLs. I'm pretty certain it's one of the best for this task. :)

nutter78
November 22nd, 2007, 11:27 AM
Thanks guys - i'm going to try Ruby!!

Kadrus
November 22nd, 2007, 06:28 PM
Honestly,I prefer Python.

Anzan
November 24th, 2007, 01:46 PM
Here's a blog post on the "enjoyment" factor of Ruby:

http://gilesbowkett.blogspot.com/2007/11/why-i-program-in-ruby-and-maybe-why-you.html

Nekiruhs
November 24th, 2007, 02:17 PM
There is just one point to consider if you want to learn Ruby. Matz and Company are currently working on Ruby 2.0 and there will be some changes to the syntax and to the language in general. This means that you'll have to learn some new things with Ruby 2.0 whereas Python won't change anymore.
Python 3.0 is in the works as well. With major version changes the Python team's philosophy is that it is ok to break backwards compatibility only on major version changes. So there will be some new constructs and functions, and potentially syntax, 3.0 might be same way as Ruby 2.0 as far a s differences.

Klipt
November 24th, 2007, 07:51 PM
yeah... I don't think the parantheses can be removed completely, but they might be made optional (in some cases)

Dylan was an attempt at Lisp with more common syntax. It still has macros (Dylan stands for DYnamic LANguage) but they are hygienic, more like Scheme's.

I don't know anyone who uses Dylan though.

I don't know enough Ruby to contribute to the discussion, although I like the way it uses blocks in custom iterators, Smalltalk style. Less powerful than macros, certainly, but more orthogonal.

ThinkBuntu
November 25th, 2007, 12:09 AM
Both are very useful, OOP-friendly languages. I found the tabbing in Python code to be very frustrating as a beginner. I have enough to worry about with language constructs and such as it is, and having best practices imposed on me definitely slowed down my progress. I think that it's more than likely that Ruby and Python press onward, with one of the two making some poorly thought-out decisions that deliver precedence to the other. I see Ruby continuing to grow outside of Japan, so we can expect the community and documentation in English to improve substantially. That being said, Python programmers far outnumber Ruby programmers outside of Japan. This is especially true for seasoned developers.

pmasiar
November 29th, 2007, 04:39 PM
Python tabbing is not issue if you use any decent syntax-aware editor. IDLE is the one bundled with Python, so there is no excuse using Notepad :-)

Ruby got a head-start with Rails, which was truly innovative way to program web apps. Since 2005 (as Google hired Guido :-) ), web apps became more visible on radar, and now Python has couple web app frameworks comparable with Rails: Django and Turbogears (and Pylons if you are hardcore).

But Python is widely used beyond web apps, like biology/genetics, computer graphics, numerical processing (always scripting usage of fast C libraries). Ruby will have hard time to beat that, also because it's Perlish syntax.

asimon
November 30th, 2007, 10:02 PM
Python tabbing is not issue if you use any decent syntax-aware editor. IDLE is the one bundled with Python, so there is no excuse using Notepad :-)
It's a non-issue with any decent editor, but can be annoying if you are into metaprogramming.


and now Python has couple web app frameworks comparable with Rails: Django and Turbogears (and Pylons if you are hardcore).
They are comparable but IMO not as beautiful, with Ruby's syntax you can just produce much more natural and readable code and DSLs.


But Python is widely used beyond web apps, like biology/genetics, computer graphics, numerical processing (always scripting usage of fast C libraries). Ruby will have hard time to beat that, also because it's Perlish syntax.
Ruby is used for all these things too (and was before Rails), although it's not as popular there as Python. But if we want to use the language which is more popular, we would use neither Python nor Ruby.

I recommend to have a look at both languages and just use what makes more sense for you. Reading tutorials for both languages is no waste of time.

Majorix
November 30th, 2007, 11:12 PM
Last time I checked this poll's results (only a week ago or so) Ruby was following with less than 31%. Now it's close to 33%. Do you think Ruby is becoming more and more popular over time nowadays?

LaRoza
November 30th, 2007, 11:14 PM
Last time I checked this poll's results (only a week ago or so) Ruby was following with less than 31%. Now it's close to 33%. Do you think Ruby is becoming more and more popular over time nowadays?

This poll hardly indicates a global trend.

Ruby is spreading beyond its Asian origins, but Python is becoming more widespread also. With IronPython, and the fact that Python comes with Mac OSX, and is usually installed with Linux, Python will continue to spread.

Majorix
November 30th, 2007, 11:26 PM
It's just a matter of a momentary decision before that changes. A developer group might decide to just install Ruby alongside Python on a Linux distro, and I believe it already comes installed with Mac OSX (even though broken from what I read). And don't forget that Java, the widest spread programming language, doesn't come installed with the widest spread OS (which we all sadly guess).

LaRoza
November 30th, 2007, 11:45 PM
It's just a matter of a momentary decision before that changes. A developer group might decide to just install Ruby alongside Python on a Linux distro, and I believe it already comes installed with Mac OSX (even though broken from what I read). And don't forget that Java, the widest spread programming language, doesn't come installed with the widest spread OS (which we all sadly guess).

I am not saying Ruby is not spreading, it is. It's increase in popularity doesn't mean a decrease in the popularity of another language.

Ruby may make it as far as Python and Perl have gotten to date, but I have my doubts, because it is mostly used with RoR, and doesn't fulfill some gap in programming.

asimon
December 1st, 2007, 02:24 AM
Do you think Ruby is becoming more and more popular over time nowadays?
Yes (http://www.tiobe.com/tpci.htm).

pmasiar
December 1st, 2007, 07:19 PM
Last time I checked this poll's results (only a week ago or so) Ruby was following with less than 31%. Now it's close to 33%. Do you think Ruby is becoming more and more popular over time nowadays?

There are lies, damned lies, and statistics (http://en.wikipedia.org/wiki/Lies,_damned_lies,_and_statistics), and beyond that, there are online polls :-)

No poll conducted by self-selecting participants can have even glimpse of the reality, as you will learn in Statistics 101.

Ruby is popular, especially by people sick of Java web app development, but it's design was not intended to be as clear as Python, and it will contribute to Ruby's undoing - but only after 10 years of being popular web app language.

Ruby and Python are neck to neck, Ruby is newer so has more hype, but Python has much bigger base: Google, Cannonical, OLPC guarantee Python will survive.