LoginSignup
0
0

More than 3 years have passed since last update.

RubyでルールのあるSortプログラムを作る

Last updated at Posted at 2020-02-16

はじめに

rubyでオリジナルのソートを作るためのメモ
JSONが入っているのは自分のローカルサーバで作りやすかったから

コード

ruby.rb
require 'json'

$jsonfile = <<EOF
[{"id":643,"name":"7_to_7_3","tag":"ミットナイトレストラン7to703,胡桃ちの,漫画","created_at":"2018-12-02T11:30:34.013Z","updated_at":"2018-12-02T11:30:34.013Z"},
{"id":644,"name":"7_to_7_4","tag":"ミットナイトレストラン7to704,胡桃ちの,漫画","created_at":"2018-12-02T11:31:05.979Z","updated_at":"2018-12-02T11:31:05.979Z"},
{"id":641,"name":"7_to_7_10","tag":"ミットナイトレストラン7to710,胡桃ちの,漫画","created_at":"2018-11-29T12:01:43.992Z","updated_at":"2018-11-29T12:01:43.992Z"},
{"id":645,"name":"7_to_7_11","tag":"ミットナイトレストラン7to711,胡桃ちの,漫画","created_at":"2018-12-02T11:31:47.163Z","updated_at":"2018-12-02T11:31:47.163Z"}]
EOF

def num_kaiseki(str)
    output = []
    tmp = str
    num = str.rindex(/[0-9]/)
    out =""
    count = 0
    if (num !=nil)
        while(tmp[num-count])
            if (tmp[num-count]=="_")
            elsif (tmp[num-count].index(/[0-9]/)==nil)
                if(out[0]==".")
                    out = out[1..tmp.size]
                end
                break
            end
            if (tmp[num-count]=="_")
                out = "."+out
            else
                out = tmp[num-count]+out
            end
            count+=1
        end
    else
        num = tmp.size
    end
    output = [tmp[0..tmp.size-out.size-1] ,out.to_f]
end
def sort_jouken(a,b)
    t_a = num_kaiseki(a)
    t_b = num_kaiseki(b)
    if (t_a[0] == t_b[0])
        output = t_a[1]<=>t_b[1]
    else
        output = t_a[0]<=>t_b[0]
    end
    output
end

list = JSON.parse($jsonfile)
list.each do |word|
    p num_kaiseki(word["name"])
end
bb = list.sort { |a,b| sort_jouken(a["name"],b["name"]) }
bb.each do|word|
    print word["id"],":",word["name"],","
end

不満点

小数点のルール条件めちゃくちゃだから、どうにかしないと

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0