LoginSignup
17
16

More than 5 years have passed since last update.

Rubyの配列でswap(入れ替え)メソッド

Last updated at Posted at 2015-07-14

Rubyで配列の中身を入れ替えたいときのswapメソッドをふと考えました。
コンセプトとしてはarray.swap!(a, b)でarrayのa番目とb番目の要素が入れ替わるメソッドです。

Arrayクラスに以下の様に定義しました。Array#swapは非破壊メソッド、Array#swap!は破壊メソッドです。

定義

class Array
  def swap!(a, b)
    raise ArgumentError unless a.between?(0, self.count-1) && b.between?(0, self.count-1)

    self[a], self[b] = self[b], self[a]

    self
  end

  def swap(a, b)
    self.dup.swap!(a, b)
  end
end

実行結果

irb(main):014:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb(main):015:0> a.swap(0, 3)
=> [4, 2, 3, 1, 5]
irb(main):016:0> a
=> [1, 2, 3, 4, 5]
irb(main):017:0> a.swap!(1, 4)
=> [1, 5, 3, 4, 2]
irb(main):018:0> a
=> [1, 5, 3, 4, 2]
17
16
2

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
17
16