[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Need examples comparing Ruby to Python
From:       David MacQuigg <dmq () gain ! com>
Date:       2004-02-24 19:49:49
Message-ID: kf9n30pasdllgdi87qjeur062tjanu90bs () 4ax ! com
[Download RAW message or body]

On Tue, 24 Feb 2004 18:52:28 +0100, Florian Gross <flgr@ccan.de>
wrote:
>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. ;)

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


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic