unintended consequence: string.sort

Discussion in 'Ruby' started by Martin DeMello, Jul 5, 2007.

  1. irb(main):001:0> "hello world".sort
    => ["hello world"]

    (Because Enumerable#sort calls to_a, and String#to_a = [string])

    However this is inconsistent with String#each, and almost certainly
    never what the user wants. I'd suggest
    String.split($/).sort.join($/).

    martin
    Martin DeMello, Jul 5, 2007
    #1
    1. Advertising

  2. Martin DeMello

    Guest

    Hi --

    On Thu, 5 Jul 2007, Martin DeMello wrote:

    > irb(main):001:0> "hello world".sort
    > => ["hello world"]
    >
    > (Because Enumerable#sort calls to_a, and String#to_a = [string])
    >
    > However this is inconsistent with String#each, and almost certainly
    > never what the user wants. I'd suggest
    > String.split($/).sort.join($/).


    I don't think it's inconsistent with String#each:

    >> "hello world".each {|x| p x }

    "hello world"

    If you have multiple lines it will sort that way:

    >> "hello\nworld".sort

    => ["hello\n", "world"]


    David

    --
    * Books:
    RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
    RUBY FOR RAILS (http://www.manning.com/black)
    * Ruby/Rails training
    & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)
    , Jul 5, 2007
    #2
    1. Advertising

  3. On 7/5/07, <> wrote:

    > If you have multiple lines it will sort that way:
    >
    > >> "hello\nworld".sort

    > => ["hello\n", "world"]


    Huh - I thought I tried that and it didn't work. Would still be nicer
    for it to return a string (since it can), but I agree it's consistent.

    martin
    Martin DeMello, Jul 5, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. sotec
    Replies:
    1
    Views:
    8,123
    =?Utf-8?B?UGV0ZXIgQnJvbWJlcmcgW0MjIE1WUF0=?=
    Dec 30, 2005
  2. Kay Schluehr

    Unintended inheritance

    Kay Schluehr, Feb 20, 2006, in forum: Python
    Replies:
    2
    Views:
    441
    Kay Schluehr
    Feb 24, 2006
  3. Andreas Griesmayer

    GCC-Bug ? (Unintended "overloading")

    Andreas Griesmayer, Jul 31, 2006, in forum: C Programming
    Replies:
    20
    Views:
    577
    Ike Naar
    Aug 2, 2006
  4. Aldric Giacomoni
    Replies:
    4
    Views:
    208
    Aldric Giacomoni
    Dec 16, 2008
  5. Replies:
    2
    Views:
    190
    smallpond
    Apr 29, 2009
Loading...

Share This Page