Need examples comparing Ruby to Python


(David MacQuigg) #1

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

Take a look at http://userlinux.com/cgi-bin/wiki.pl?RubyPython This
is part of the UserLinux project, a new Linux distribution that I hope
will pick up where Red Hat left off, and be easier to install than
Debian. Python is our chosen “primary” scripting language, but there
are many participants who are also interested in Ruby.

Thanks for your help.

– David MacQuigg


(Emmanuel Touzery) #2

David MacQuigg wrote:

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

the ruby code could be simplified:

file, length, name, title = line.chomp.split(/\s*|\s*/)
name.squeeze!(" ")
=>
file, length, name, title =line.split /|/
name.strip!

also, if min and sec are numbers, they should be kept in number
variables imho. but it makes the code look more complicated to newbyes
so it’s discussable:
mins, secs = length.scan(/\d+/)
songs.append Song.new(title, name, mins.to_i60+secs.to_i)
=>
mins,secs = length.scan(/\d+/).map {|i| i.to_i}
songs.append Song.new(title, name, mins
60+secs)


(Emmanuel Touzery) #3

Hello,

David MacQuigg wrote:

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

and good luck for your project!

i would personnally emphasize select, find, the & array operator which
is array intersection, sort_by, and this kind of cool ruby features
found in Enumerable. But I don’t know how python does it.

emmanuel


(Laurent Julliard) #4

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

imo, python and ruby offer enough feature to be interchangeable.
I think it’s more a matter of taste.

Take a look at http://userlinux.com/cgi-bin/wiki.pl?RubyPython This
is part of the UserLinux project, a new Linux distribution that I hope
will pick up where Red Hat left off, and be easier to install than
Debian. Python is our chosen “primary” scripting language, but there
are many participants who are also interested in Ruby.

in the end, the quote should be
"Ruby does not have immutable objects like tuples. Using ! will
modify an object in-place, but you can make any object immutable with
freeze()"

but maybe, you should undeline that ruby has had oo+iterators since
the beginning, while python added them later. This reflects in the
’feeling’ of the language, I believe

···

il Mon, 23 Feb 2004 07:47:12 -0700, David MacQuigg dmq@gain.com ha scritto::


(Kent S.) #5

Even though it’s nice to know about these small differences in both
languages, I think all these examples miss their target. The biggest win
I get when I use Ruby is that it allows me to program at the meta level.
As in Dave Thomas’ example, Ruby allows me to do things like this

 class RegionTable < Table
  table "region" do
    field autoinc, :reg_id,        pimary_key
    field int,     :reg_affiliate, references(AffiliateTable)
    field varchar(100), :reg_name
  end
 end

which basically means that I can create my own
DomainSpecificLanguage(http://martinfowler.com/bliki/DomainSpecificLanguage.html)
without leaving Ruby. I don’t know much about Python but I don’t think
it is that easy to do with it.

/kent

David MacQuigg wrote:

···

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

Take a look at http://userlinux.com/cgi-bin/wiki.pl?RubyPython This
is part of the UserLinux project, a new Linux distribution that I hope
will pick up where Red Hat left off, and be easier to install than
Debian. Python is our chosen “primary” scripting language, but there
are many participants who are also interested in Ruby.

Thanks for your help.

– David MacQuigg


(James Britt) #6

David MacQuigg wrote:

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

There are some pointers here:

http://www.ruby-doc.org/RubyEyeForThePythonGuy.html

James


(David A. Black) #7

Hi –

David MacQuigg wrote:

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

the ruby code could be simplified:

file, length, name, title = line.chomp.split(/\s*|\s*/)
name.squeeze!(" ")
=>
file, length, name, title =line.split /|/
name.strip!

That doesn’t do the same thing though:

irb(main):029:0> " Song Title ".strip
=> "Song Title"
irb(main):030:0> " Song Title ".squeeze
=> " Song Title "

also, if min and sec are numbers, they should be kept in number
variables imho. but it makes the code look more complicated to newbyes
so it’s discussable:
mins, secs = length.scan(/\d+/)
songs.append Song.new(title, name, mins.to_i*60+secs.to_i)
=>
mins,secs = length.scan(/\d+/).map {|i| i.to_i}

or:

require 'scanf’
mins,secs = length.scanf("%d:%d")

David

···

On Mon, 23 Feb 2004, Emmanuel Touzery wrote:


David A. Black
dblack@wobblini.net


(Carlos) #8

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

the ruby code could be simplified:

file, length, name, title = line.chomp.split(/\s*|\s*/)
name.squeeze!(" ")
=>
file, length, name, title =line.split /|/
name.strip!

Do you realize that then ‘file’ will hold "/jazz/j00319.mp3 "?
He’s avoiding spaces around “|” for a reason.

Also, with your “correction” the spaces between “Louis” and
"Armstrong" in the name won’t be squeezed.


(David MacQuigg) #9

in the end, the quote should be
"Ruby does not have immutable objects like tuples. Using ! will
modify an object in-place, but you can make any object immutable with
freeze()"

Good point. I’ve changed the statement in the wiki.

but maybe, you should undeline that ruby has had oo+iterators since
the beginning, while python added them later. This reflects in the
’feeling’ of the language, I believe

I’m trying to avoid differences that are no longer true, and stay
neutral with regard to matters of personal preference, like the "feel"
of the language. This should get us down to just a few examples where
Ruby has an advantage.

There probably aren’t any simple examples left, since Python has added
a lot in the last few years. Still, I think there may be a difference
with examples that are a little more complex.

I’ve been playing around with a modification of the “jukebox” example.
If we have a problem requiring several string operations in sequence,
we run into some missing methods in Python, and have to resort to
either mappings or list comprehensions, which are not as simple and
readable as a sequence of methods applied to the starting object.

Here is what I would like to say in Python, but can’t because
line.split() produces a list, and the subsequent methods don’t apply
to lists. I’ll bet this would work in Ruby, but I don’t know enough
Ruby to say for sure.

file, length, name, title = line.split(’|’).strip.split.join()

The goal is to produce a list of strings with whitespace and newlines
stripped off the ends, and whitespace squeezed out of the middle of
each string.

The equivalent statement in Python, using OOP style and list
comprehensions is:

file, length, name, title = [’ ‘.join(t.split()) for t in [t.strip()
for t in line.split(’|’)]]

which to me looks even worse than a pure functional style:

file, length, name, title = map(join, map(split, map(strip,
split(line, ‘|’))))

( Sorry about the formatting here. I can’t get this all on one line
in the newsreader. )

This may be our first example showing an advantage for Ruby beyond
just a preference on style. While there are those who prefer the
functional style, I think there is an advantage to a style in which
the operations are typed in the same order that you have to visualize
intermediate results. With a sequence of operations in FP style, I
find myself miscounting parentheses, and having to repeatedly go back
to the beginning of the line to insert the next operation.

If someone can show me a nice way to do this in Ruby, I’ll include it
in our language comparison page, and challenge the Python programmers
to match it in conciseness and clarity.

– Dave

···

On Mon, 23 Feb 2004 15:57:39 GMT, gabriele renzi surrender_it@remove.yahoo.it wrote:


(David MacQuigg) #10

Even though it’s nice to know about these small differences in both
languages, I think all these examples miss their target. The biggest win

I agree. The differences ended up small because I took the examples
from the Programming Ruby book, then updated the Python to a more
optimum form, taking advantage of methods added since the book was
written. I would like to replace these trivial examples with
something showing a more significant difference between these two
languages. Then we can answer the question: Do the differences come
down to just a few missing methods, which we can add ourselves, or do
we really have some fundamental advantages, perhaps enough to move off
of Python.

I get when I use Ruby is that it allows me to program at the meta level.
As in Dave Thomas’ example, Ruby allows me to do things like this

class RegionTable < Table
 table "region" do
   field autoinc, :reg_id,        pimary_key
   field int,     :reg_affiliate, references(AffiliateTable)
   field varchar(100), :reg_name
 end
end

which basically means that I can create my own
DomainSpecificLanguage(http://martinfowler.com/bliki/DomainSpecificLanguage.html)
without leaving Ruby. I don’t know much about Python but I don’t think
it is that easy to do with it.

I’m having trouble understanding the goal of this example. That is
the key to providing a meaningful comparison. Any language can do
esoteric tricks that no other language can reproduce without some
difficult coding. The latest version of Python, for example, provides
a slight variation on the multiple inheritance method resolution order
for rare cases where our parent classes have a common ancestor !!
Cool stuff, but will I ever use it?

If you need to write a paragraph or two to motivate or explain the
goals for an example of some code, we can include these details as a
footnote or link on the examples showcase page. They we can try to
get the same result in Python, perhaps using an entirely different set
of statements.

– Dave

···

On Mon, 23 Feb 2004 11:20:43 -0500, “Kent S.” happy@user.com wrote:

/kent

David MacQuigg wrote:

I’m putting together a web page comparing Ruby to Python, and I need
some good examples showing off the advantages of Ruby. I’m new to
Ruby, so all I’ve been able to do so far is pick some examples from
the Programming Ruby book, and do a Google search on “compare ruby
python”. What I’ve found is way out-of-date.

Take a look at http://userlinux.com/cgi-bin/wiki.pl?RubyPython This
is part of the UserLinux project, a new Linux distribution that I hope
will pick up where Red Hat left off, and be easier to install than
Debian. Python is our chosen “primary” scripting language, but there
are many participants who are also interested in Ruby.

Thanks for your help.

– David MacQuigg


(David MacQuigg) #11

Thanks to both Alan and James. These are both excellent links, and
I will put them on my page.

– Dave

···

On 23 Feb 2004 16:34:49 -0800, aero6dof@yahoo.com (Alan Chen) wrote:

You might be interested in the “Programming Language Examples Alike
Cookbook” pages http://pleac.sourceforge.net. They maintain
multi-language entries implementing source code examples matching
those given in the Perl Cookbook.
Python and Ruby are represented there (as well as many other
languages.).

On Tue, 24 Feb 2004 10:15:44 +0900, James Britt jamesUNDERBARb@neurogami.com wrote:

There are some pointers here:
http://www.ruby-doc.org/RubyEyeForThePythonGuy.html


(Mark Hubbart) #12

I’m getting into this a little late, but…
This takes care of it nicely, and looks pretty good:

file, length, name, title = line.chomp.squeeze.split(" | ")

And, assuming “songs” is an array:
songs << Song.new(file, length, name, title)

It’s difficult to simplify the (“m:ss” => sec) time conversion (while
still having it be readable) so I’ll just leave that one alone, thank
you. :slight_smile:

–Mark

···

On Feb 23, 2004, at 6:57 AM, Emmanuel Touzery wrote:

the ruby code could be simplified:


(Laurent Julliard) #13

I don’t think that is a personal preference :slight_smile:
I mean, in python you’ll often see free function like
len(obj) or dir(), while in ruby you’d do obj.length and obj.methods.

That reflect on other things like hash keys. There are no special type
in ruby, so you can use everything as an hash key.

Another example that suddenly appeared to me: slightly different
lexical closures:
def make_accumulator (n)
lambda {|i| n += i }
end

That is little harder in python cause you don’t have access to the
variable ‘n’ , just his object.

BTW, as I said, little differences.

···

il Mon, 23 Feb 2004 12:14:33 -0700, David MacQuigg dmq@gain.com ha scritto::

but maybe, you should undeline that ruby has had oo+iterators since
the beginning, while python added them later. This reflects in the
’feeling’ of the language, I believe

I’m trying to avoid differences that are no longer true, and stay
neutral with regard to matters of personal preference, like the "feel"
of the language. This should get us down to just a few examples where
Ruby has an advantage.


(Jim Weirich) #14

David MacQuigg said:

Here is what I would like to say in Python, but can’t because
line.split() produces a list, and the subsequent methods don’t apply
to lists. I’ll bet this would work in Ruby, but I don’t know enough
Ruby to say for sure.

file, length, name, title = line.split(’|’).strip.split.join()

The goal is to produce a list of strings with whitespace and newlines
stripped off the ends, and whitespace squeezed out of the middle of
each string.

Is this what you want …

file, length, name, title = line.split(’|’).collect{|it| t.squeeze.strip}

···


– Jim Weirich jim@weirichhouse.org http://onestepback.org

“Beware of bugs in the above code; I have only proved it correct,
not tried it.” – Donald Knuth (in a memo to Peter van Emde Boas)


(Alan Chen) #15

David MacQuigg dmq@gain.com wrote in message news:t9kk3096co36vqani3g7ctpg75bcfag8q8@4ax.com

If you need to write a paragraph or two to motivate or explain the
goals for an example of some code, we can include these details as a
footnote or link on the examples showcase page. They we can try to
get the same result in Python, perhaps using an entirely different set
of statements.

David,

You might be interested in the “Programming Language Examples Alike
Cookbook” pages http://pleac.sourceforge.net. They maintain
multi-language entries implementing source code examples matching
those given in the Perl Cookbook.
Python and Ruby are represented there (as well as many other
languages.).

Cheers,

  • alan

(Florian Gross) #16

David MacQuigg wrote:

file, length, name, title = line.split(’|’).strip.split.join()
The goal is to produce a list of strings with whitespace and newlines
stripped off the ends, and whitespace squeezed out of the middle of
each string.

This ought to work and be quite close to Ruby idioms. (Blocks are used
everywhere – and unlike Python’s lambdas they’re not limited to any
number of statements or the type of statements that may appear in them:
e.g. I can’t seem to work out a way to use print in a lambda in Python.)

file, length, name, title = line.split(’|’).map do |token|
token.strip.split.join
end

The equivalent statement in Python, using OOP style and list
comprehensions is:
file, length, name, title = [’ ‘.join(t.split()) for t in [t.strip()
for t in line.split(’|’)]]

I think I would prefer the equivalent map() solution, even if it’s less
used and more to type.

By the way – I think this is an example how Ruby was built from the
beginning with its language ideals in mind: In Ruby the whole Standard
Library is truly object-oriented and uses blocks for everything that
makes sense. (5.times { |index| … }, File.open(“foo.rb”) { |file| …
}, Array.new(5) { |index| … }, Hash.new { |hash, key| … }, [matz,
guido].sort_by { |person| … } and way more of that good stuff – just
take a look at the documentation of the Standard Library:
http://www.ruby-doc.org/docs/rdoc/1.9/)

If someone can show me a nice way to do this in Ruby […]

I hope that I did so. :wink:

Regards,
Florian Gross


(David MacQuigg) #17

the ruby code could be simplified:

I’m getting into this a little late, but…
This takes care of it nicely, and looks pretty good:

file, length, name, title = line.chomp.squeeze.split(" | ")

This squeezes everything, not just the name. But it is still the best
example I’ve seen so far of the power of Ruby in processing strings.
We do need the regex /\s*|\s*/ in case we get some data with no space
on one side or the other of the ‘|’ delimiter.

···

On Wed, 25 Feb 2004 06:20:55 +0900, Mark Hubbart discord@mac.com wrote:

On Feb 23, 2004, at 6:57 AM, Emmanuel Touzery wrote:

And, assuming “songs” is an array:
songs << Song.new(file, length, name, title)

It’s difficult to simplify the (“m:ss” => sec) time conversion (while
still having it be readable) so I’ll just leave that one alone, thank
you. :slight_smile:

–Mark


(David A. Black) #18

Hi –

···

On Tue, 24 Feb 2004, Jim Weirich wrote:

David MacQuigg said:

Here is what I would like to say in Python, but can’t because
line.split() produces a list, and the subsequent methods don’t apply
to lists. I’ll bet this would work in Ruby, but I don’t know enough
Ruby to say for sure.

file, length, name, title = line.split(’|’).strip.split.join()

The goal is to produce a list of strings with whitespace and newlines
stripped off the ends, and whitespace squeezed out of the middle of
each string.

Is this what you want …

file, length, name, title = line.split(’|’).collect{|it| t.squeeze.strip}
^^
s/it/t/ :slight_smile:

(I wonder whether it would be faster/slower/same to do:

f,l,n,t = line.squeeze.split(’|’).collect{|t| t.strip}

but I’m feeling too lazy to haul out benchmark.rb right now :slight_smile:

David


David A. Black
dblack@wobblini.net


(David MacQuigg) #19

Yes. That works if I change the ‘it’ to ‘t’. Looks like the
’collect’ method is equivalent to Python’s ‘map’ function. This
statement is still not as simple as I would like, but it definitely
beats the equivalent Python.

This is the first example I’ve seen where the difference between Ruby
and Python is more than just personal preference. Thanks.

– Dave

···

On Tue, 24 Feb 2004 06:59:10 +0900, “Jim Weirich” jim@weirichhouse.org wrote:

David MacQuigg said:

Here is what I would like to say in Python, but can’t because
line.split() produces a list, and the subsequent methods don’t apply
to lists. I’ll bet this would work in Ruby, but I don’t know enough
Ruby to say for sure.

file, length, name, title = line.split(’|’).strip.split.join()

The goal is to produce a list of strings with whitespace and newlines
stripped off the ends, and whitespace squeezed out of the middle of
each string.

Is this what you want …

file, length, name, title = line.split(’|’).collect{|it| t.squeeze.strip}


(David MacQuigg) #20

David MacQuigg wrote:

file, length, name, title = line.split(’|’).strip.split.join()
The goal is to produce a list of strings with whitespace and newlines
stripped off the ends, and whitespace squeezed out of the middle of
each string.

This ought to work and be quite close to Ruby idioms. (Blocks are used
everywhere – and unlike Python’s lambdas they’re not limited to any
number of statements or the type of statements that may appear in them:
e.g. I can’t seem to work out a way to use print in a lambda in Python.)

I’m not seeing any fundamental advantage of Ruby blocks over Python
functions. If your block is more than one line, or needs a print
statement, just give it a name and let it be a function. lambda’s are
used only for very short blocks, where for example, you want to pass a
simple function in an argument list, but don’t want to waste a line
giving that function a name. I like Ruby’s more compact |x| instead
of Python’s keyword - lambda x: - but that is just my personal
preference.

file, length, name, title = line.split(’|’).map do |token|
token.strip.split.join
end

The equivalent statement in Python, using OOP style and list
comprehensions is:
file, length, name, title = [’ ‘.join(t.split()) for t in [t.strip()
for t in line.split(’|’)]]

I think I would prefer the equivalent map() solution, even if it’s less
used and more to type.

I agree. That ’ '.join method is really ugly.

By the way – I think this is an example how Ruby was built from the
beginning with its language ideals in mind: In Ruby the whole Standard
Library is truly object-oriented and uses blocks for everything that
makes sense. (5.times { |index| … }, File.open(“foo.rb”) { |file| …
}, Array.new(5) { |index| … }, Hash.new { |hash, key| … }, [matz,
guido].sort_by { |person| … } and way more of that good stuff – just
take a look at the documentation of the Standard Library:
http://www.ruby-doc.org/docs/rdoc/1.9/)

If someone can show me a nice way to do this in Ruby […]

I hope that I did so. :wink:

Yes. The example above is definitely better than the Python I have so
far. I’ll include this (in its shorter one-line form) on my
comparison page.

– Dave

···

On Tue, 24 Feb 2004 18:52:28 +0100, Florian Gross flgr@ccan.de wrote: