Rubyのmapとeach、scanの使い方
Rubyのmapとeach、scanの使い方
チェリー本4章に出てきた内容ですが、実際に過程をまとめました。
16進数を10進数の配列に変換するメソッドを作成しています。
①each
?> def to_ints(hex) ?> r = hex[1..2] ?> g = hex[3..4] ?> b = hex[5..6] ?> results = [] ?> [r, g, b].each do |n| ?> results << n.hex ?> end ?> results >> end => :to_ints >> >> to_ints('#ffffff') => [255, 255, 255]
②map
?> def to_ints(hex) ?> r = hex[1..2] ?> g = hex[3..4] ?> b = hex[5..6] ?> [r, g, b].map do |n| ?> n.hex ?> end >> end => :to_ints >> >> to_ints('#ffffff') => [255, 255, 255]
③doとend省略
?> def to_ints(hex) ?> r = hex[1..2] ?> g = hex[3..4] ?> b = hex[5..6] ?> [r, g, b].map { |n| n.hex } >> end => :to_ints >> >> to_ints('#ffffff') => [255, 255, 255]
④ブロック変数省略
?> def to_ints(hex) ?> r = hex[1..2] ?> g = hex[3..4] ?> b = hex[5..6] ?> [r, g, b].map(&:hex) >> end => :to_ints >> >> to_ints('#ffffff') => [255, 255, 255]
⑤正規表現で多重変数代入
?> def to_ints(hex) ?> r, g, b = hex.scan(/\w\w/) ?> [r, g, b].map(&:hex) >> end => :to_ints >> >> to_ints('#ffffff') => [255, 255, 255]
⑥一行にまとめる
?> def to_ints(hex) ?> hex.scan(/\w\w/).map(&:hex) >> end => :to_ints >> >> to_ints('#ffffff') => [255, 255, 255]
すごくいい問題でした。