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

List:       ruby-talk
Subject:    Re: Need examples comparing Ruby to Python
From:       Florian Gross <flgr () ccan ! de>
Date:       2004-02-24 17:54:49
Message-ID: c1g30o$1hei96$1 () ID-7468 ! news ! uni-berlin ! de
[Download RAW message or body]

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. ;)

Regards,
Florian Gross

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

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