yamadagenki0607
yamadagenki0607
2015/12/10 17:19:18 投稿
0

「【Refactor Me】複数の配列の要素を並び替えるコードをリファクタリング」をやってみた

とにかく短くする

Before

def sort_lists(a, b)
  a.sort!
  b.sort!
  b.size.times do |i|
    a.size.times do |j|
      x, y = a[j], b[i]
      if y < x
        a[j] = y
        b[i] = x
      else
        next
      end
    end
  end
  b.sort!

  [a, b]
end

require 'minitest/autorun'

class TestSortLists < Minitest::Test
  def self.test_sort_lists
    data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].shuffle
    assert_equal([['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']], sort_lists(data[0..3], data[4..7]))
  end
end

After

def sort_lists(a, b)
  head_length = a.length
  sorted_data = a.concat(b).sort

  [sorted_data[0..(head_length-1)], sorted_data[head_length..sorted_data.length-1]]
end

require 'minitest/autorun'

class TestSortLists < Minitest::Test
  def test_sort_lists
    data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].shuffle
    assert_equal([['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']], sort_lists(data[0..3], data[4..7]))
  end
end

みんなのコメント