sort ... by ... of each is far more powerful than I knew

Geoff Canyon gcanyon at gmail.com
Mon Sep 16 22:35:47 EDT 2013


I was wondering all through that, "Does Ruby support automatic item-parsing
by index somehow?" until I saw the splits at the end.

I just did a quick test, and found that using "of each" inline is faster
than sorting by a function on each. The syntax for an inline "of each" can
get needlessly complex I suppose, although I've never run into a real-world
problem that required something funky.


On Mon, Sep 16, 2013 at 2:31 PM, Mark Wieder <mwieder at ahsoftware.net> wrote:

> Richard-
>
> Monday, September 16, 2013, 6:50:46 AM, you wrote:
>
> > If someone has time on their hands it might be fun to see what Python
> > and JavaScript versions of each of those would look like.
>
> Well, that was fun. Here it is in ruby:
>
> # ruby 1.9.3
>
> #sort lines of x numeric ascending by item 3 of each
> def func1(x)
>         x[2].to_i
> end
>
> # sort lines of x numeric ascending by item 3 of each * word 2 of item 1
> of each
> def func2(x)
>         x[2].to_i * x[0].split[1].to_i
> end
>
> #sort lines of x numeric descending by abs(item 3 of each * word 2 of item
> 1 of each)
> def func3(x)
>         -(x[2].to_i * x[0].split[1].to_i).abs
> end
>
> #sort lines of x by item 3 of each > word 2 of item 1 of each
> def func4(x)
>         (x[2].to_i > x[0].split[1].to_i) ? 1 : 0
> end
>
> #sort lines of x by (item 3 of each > word 2 of item 1 of each) && item 4
> of each
> def func5(x)
>         (x[2].to_i > x[0].split[1].to_i).to_s + x[3]
> end
>
> #sort lines of x numeric descending by length(item 4 of each) - (item 3 of
> each)
> def func6(x)
>         -(x[3].length - x[2].to_i)
> end
>
> # see if it works...
> def parse_test
>         data = [
>                 "test 1,this,5,apple",
>                 "test 2,the,-2,pear",
>                 "test 3,a,2,grape",
>                 "test 4,oh,0,strawberry"
>         ]
>         p data.sort_by { |w| func1(w.split(","))}
>         p data.sort_by { |w| func2(w.split(","))}
>         p data.sort_by { |w| func3(w.split(","))}
>         p data.sort_by { |w| func4(w.split(","))}
>         p data.sort_by { |w| func5(w.split(","))}
>         p data.sort_by { |w| func6(w.split(","))}
> end
>
> parse_test
>
> --
> -Mark Wieder
>  mwieder at ahsoftware.net
>
>
> _______________________________________________
> use-livecode mailing list
> use-livecode at lists.runrev.com
> Please visit this url to subscribe, unsubscribe and manage your
> subscription preferences:
> http://lists.runrev.com/mailman/listinfo/use-livecode
>



More information about the use-livecode mailing list