ruby %w equivalent

Nick Craig-Wood nick at craig-wood.com
Wed Sep 27 04:30:04 EDT 2006


MonkeeSage <MonkeeSage at gmail.com> wrote:
>  In ruby there are several special literal notations, just like python.
>  In ruby it goes like this:
> 
>  %{blah} / %Q{blah} # same as "blah" but igornes " and '
>  %q{blah} # same as 'blah' but no interpolation
>  %w{blah blah} # same as "blah blah".split
>  %r{blah} # same as /blah/
>  %x{ls} # same as `ls`

These are snatched straight from perl.  In perl they are spelt
slightly differently

  q{blah}       r"""blah""" # not identical but similar
  qq{blah}      """blah"""  # no interpolation in python so no direct concept
  qw{blah blah} "blah blah".split()
  qr{blah}      re.compile(r"blah")
  qx{ls}        commands.getoutput("ls")

In perl (and maybe in ruby I don't know) the { } can be replaced with
any two identical chars, or the matching pair if bracketty, so q/blah/
or q(blah).

As a perl refugee, the only one I miss at all is qw{}, ie %w{} in ruby
the subject of this post.

In python when making __slots__ or module.__all__ you end up typing
lists of objects or methods and they turn out like this which is quite
a lot of extra typing

  __slots__ = ["method1", "method2", "method3", "method4", "method5"]

You can of course write it like this

  __slots__ = "method1 method2 method3 method4 method5".split()

which is nearly as neat as qw//, but not quite since the split() bit
comes at the end so it doesn't notify you that you have an array of
strings rather than a string.

I don't expect a replacement for %w{}, qw// to ever be added to
python, it is not the python way.  And the python way is why I am now
a python programmer not a perl programmer!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list