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

Mark Wieder mwieder at ahsoftware.net
Mon Sep 16 15:31:05 EDT 2013


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





More information about the use-livecode mailing list