LoginSignup
3
3

More than 5 years have passed since last update.

Array#duplicate(Array#uniqの逆)

Posted at

Array#duplicate

Array#uniqの逆のことをやりたかった。

ついでに要素を1つだけ削除するdelete_firstdelete_lastも定義。
(Array#deleteだと全ての要素が削除される。)

class Array
  def delete_first(obj)
    if i = index(obj)
      delete_at(i)
    end
  end

  def delete_last(obj)
    if i = rindex(obj)
      delete_at(i)
    end
  end

  def duplicate!
    unless (u = uniq).size == size
      u.each do |obj|
        delete_first(obj)
      end
      self
    end
  end

  def duplicate
    clone.duplicate! || []
  end
end
sample
a = [1,'x',2,'x','y','y',3,'x']
p a
p a.duplicate
p a
p a.duplicate!
p a
result
[1, "x", 2, "x", "y", "y", 3, "x"]
["x", "y", "x"]
[1, "x", 2, "x", "y", "y", 3, "x"]
["x", "y", "x"]
["x", "y", "x"]

n個重複してる要素はn個返ってきます。

to do

  • ブロック渡せるようにする。(Array#uniqだと渡せる)
  • "duplicate"は複製という意味もあるので紛らわしい気がする。実際にObject#dupあるし。
3
3
0

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
3
3