12
8

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 5 years have passed since last update.

[ruby]二次元配列の2次元目の要素番号を指定してピックアップしたいとき。

Last updated at Posted at 2017-06-13

以下のような二次元配列の、
"1"にあたるところを抜き出したい。

array = [
  [1,2,3],
  [1,2,3],
  [1,2,3]
]

transposeを使って、行列で言う転置を行う。

array.transpose
=>
[
  [1,1,1],
  [2,2,2],
  [3,3,3]
]

そうすれば、
元々の二次元配列の2次元目の要素番号を指定してピックアップできる。

array = [
  [1,2,3],
  [1,2,3],
  [1,2,3]
]
array.transpose[0] # [1,1,1]
array.transpose[1] # [2,2,2]
array.transpose[2] # [3,3,3]

おまけ:使いどころはHashのsort

Hashのsortで並び替えを行うと返り値がArray型になります。
ちなみにsortの処理内容ははvalueの降順。(http://ref.xaio.jp/ruby/classes/hash/sort

hash = {1=>2, 2=>5, 3=>1}
hash.sort{|(k1, v1), (k2, v2)| v2 <=> v1 }

並び替えした後、hashの時keyだった値だけ引っ張りたい時、
以下のように、transposeを使う。

hash = {1=>2, 2=>5, 3=>1}
hash.sort{|(k1, v1), (k2, v2)| v2 <=> v1 }.transpose[0]
# => [2,1,3]

おまけ2:100万倍楽な方法

@scivolaさんのコメントより引用

array.map{|row| row[0]} # => [1,1,1]
array.map{|row| row[1]} # => [2,2,2]
array.map{|row| row[2]} # => [3,3,3]
12
8
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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?