@m_seki の

I like ruby tooから引っ越し

toRuby 4thの落ち穂拾い

コードレビューの件ね。解説が足りなかったのでここに載せます。

# 最初の作戦
def index_of_sorted_00(ary)
  tmp = []
  ary.each_with_index do |v, idx|
    tmp << [v, idx]
  end
  tmp.sort!
  tmp.collect {|pair| pair[1]}
end
# 破壊的メソッドなsort!がいけてない。

# sortとcollectを一行に
def index_of_sorted_01(ary)
  tmp = []
  ary.each_with_index do |v, idx|
    tmp << [v, idx]
  end
  tmp.sort.collect {|pair| pair[1]}
end
# tmpの生成をどうしよう‥

# idxを外に出してcollectはどうだろ
def index_of_sorted_02(ary)
  idx = -1
  tmp = ary.collect do |v|
    idx += 1
    [v, idx]
  end
  tmp.sort.collect {|pair| pair[1]}
end
# うわっ、かっこわるい

# zip使ってみる?
def index_of_sorted_03(ary)
  idx = 0...(ary.size)
  tmp = ary.zip(idx.to_a)
  tmp.sort.collect {|pair| pair[1]}
end
# うーん。Rangeの生成いまいち

# じゃあRange.new
def index_of_sorted_04(ary)
  idx = Range.new(0, ary.size, true)
  tmp = ary.zip(idx.to_a)
  tmp.sort.collect {|pair| pair[1]}
end
# to_aが哀しい

# あれ? aryに添字をくっつけてsortさせるんじゃなくて、
# 0...sizeをaryに従ってsortした方がよい??
def index_of_sorted_05(ary)
  idx = Range.new(0, ary.size, true)
  idx.sort_by {|i| ary[i]}
end

# 二行をくっつけてみようっと
def index_of_sorted(ary)
  Range.new(0, ary.size, true).sort_by {|idx| ary[idx]}
end


# test
src = %W(e f c d)

p index_of_sorted_00(src)
p index_of_sorted_01(src)
p index_of_sorted_02(src)
p index_of_sorted_03(src)
p index_of_sorted_04(src)
p index_of_sorted_05(src)
p index_of_sorted(src)