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?

More than 1 year has passed since last update.

Rubyのmapメソッドについて

Posted at

本記事では実務でよく使うmapメソッドの使い方について解説していきます。

【基本的な使い方】

## mapは配列に対して使います。
## 配列の要素を1つずつ取り出し、{}の処理を行います。
animal = ["dog", "cat", "koara","bird"]

## 繰り返しの処理結果が一つずつ配列に追加されていきます。
animal.map {|a| a.length}

## 返り値は配列となります。
=> [3, 3, 5, 4]

【便利な書き方】

## 以下のように「&:メソッド名」の書き方で繰り返しの要素それぞれでメソッドを呼び出せる
配列.map{&:メソッド名}

【配列の要素を全て文字列に変換】

## 一つ前に紹介した便利な書き方で実装してみる
ary = [1, 2, 3, 4]
ary.map(&:to_s)
=> ["1", "2", "3", "4"]

【with_indexを扱う書き方】

ary.map.with_index{ |n,i|
    #処理
}

## 開始のindexを指定する書き方は以下
ary.map.with_index(1){ |n,i|
    #処理
}
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?