Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | 二次元配列の各要素を元にブロックを実行し、戻り値の配列を返却する

概要

二次元配列の各要素を元にブロックを実行し、戻り値の配列を返却する

詳細

tbpgr_utils gemのArray#together_map(別名でtmap, together_collect, tcollectもあり)
二次元配列の各要素を元にブロックを実行し、戻り値の配列を返却します。

ブロックの戻り値を1個のオブジェクトにすると1次元配列、
ブロックの戻り値をN個のオブジェクトにするとN次元配列、
を返却します。

事前準備
gem install tbpgr_utils
主な用途

二次元配列の各要素を元にブロックを実行し、戻り値の配列を取得したい場合。

サンプルコード
# encoding: utf-8
require 'tbpgr_utils'

print [[*1..5], [*5..9]].together_map { |first, second|"#{first}:#{second}" }
puts
print [[*1..5], [*5..9]].together_map { |first, second|[first + 1, second + 1] }
puts
print [[*1..5], [*5..9], [*10..14]].tmap { |first, second, third|"#{first}:#{second}:#{third}" }
puts
print [[*1..5], [*5..9], [*10..14], [*11..15]].together_collect { |first, second, third, fourth|"#{first}:#{second}:#{third}:#{fourth}" }
puts
print [[*1..5], [*5..9], [*10..14], [*15..19],[*20..24]].tcollect { |first, second, third, fourth, fifth|"#{first}:#{second}:#{third}:#{fourth}:#{fifth}" }
出力
["1:5", "2:6", "3:7", "4:8", "5:9"]
[[2, 3, 4, 5, 6], [6, 7, 8, 9, 10]]
["1:5:10", "2:6:11", "3:7:12", "4:8:13", "5:9:14"]
["1:5:10:11", "2:6:11:12", "3:7:12:13", "4:8:13:14", "5:9:14:15"]
["1:5:10:15:20", "2:6:11:16:21", "3:7:12:17:22", "4:8:13:18:23", "5:9:14:19:24"]