4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rubyで配列の要素を検索置換する方法

Last updated at Posted at 2020-02-20

WEB企業の研修中に学んだ事のアウトプットです。
配列の要素を検索し、その要素を別のオブジェクトで置換する方法です。
そういうメソッドがありそうですが、ないので工夫する必要があります。

一般的な方法

array = ["foo","bar","baz"]

# arrayから"bar"を検索して"hoge"で置換します。
array.map!{|x| x=="bar" ? "hoge" : x}

puts array
#=> ["foo","hoge","baz"]

微妙な方法

※この方法でも検索置換できますが、検索ワードが配列に存在しない場合エラーになります。

array = ["foo","bar","baz"]

# arrayから"bar"を検索して"hoge"で置換します。
array[array.index("bar")] = "hoge"

puts array
#=> ["foo","hoge","baz"]
4
6
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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?