0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rubyで配列から複数の値を削除する

Posted at

Rubyで配列から複数の値を削除する方法が分からなかったので調べました。

元となる配列base_listと削除したい文字が入っている配列delete_listは以下です。

base_list = [1, 2, 2, 3, 'hoge', 'fuga', 'piyo'] # 元の配列
# => [1, 2, 2, 3, "hoge", "fuga", "piyo"]

delete_list = [2, 'fuga'] # 削除したい文字の配列
# => [2, "fuga"]

-(マイナス) 指定した配列の要素を取り除いた新しい配列を返す

-」を使って、元の配列 - 削除したい文字とすることで、指定文字が削除された新しい配列が作成されます。

new_list = base_list - delete_list
# => [1, 3, "hoge", "piyo"]

元の配列には変化はありません。

base_list
# => [1, 2, 3, "hoge", "fuga", "piyo"]

difference 指定した配列の要素を取り除いた新しい配列を返す

differenceメソッドでも同じようなことができます。

base_list = [1, 2, 2, 3, 'hoge', 'fuga', 'piyo'] # 元の配列
# => [1, 2, 2, 3, "hoge", "fuga", "piyo"]

delete_list = [2, 'fuga'] # 削除したい文字の配列
# => [2, "fuga"]

new_list = base_list.difference(delete_list)
# => [1, 3, "hoge", "piyo"]

delete 指定した文字を自身から取り除く

指定した1文字だけをすべて削除したい場合はdelete()も使えます。

base_list = [1, 2, 2, 3, 'hoge', 'fuga', 'piyo'] # 元の配列
# => [1, 2, 2, 3, "hoge", "fuga", "piyo"]

base_list.delete(2) # 2を削除

base_list # 元の配列
# => [1, 3, "hoge", "fuga", "piyo"]

参考

instance method Array#-

instance method Array#difference

instance method Array#delete

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?