プロを目指す人のためのRuby入門 その20
第10章 yield と Proc を理解する
前回に引き続き、yield と Proc について学びます。
文字の装飾
Proc を使ったコードのテストを行います。
effects.rb
module Effects def self.reverse # Proc オブジェクトをメソッドの戻り値にする ->(words) do words.split(' ').map(&:reverse).join(' ') end end def self.echo(rate) ->(words) do # スペースはそのまま # スペース以外は指定回数文字を繰り返す words.chars.map { |c| c == ' ' ? c : c * rate }.join end end end
effects_test.rb
require 'minitest/autorun' require './lib/effects' class EffectTest < Minitest::Test def test_reverse effect = Effects.reverse assert_equal 'ybuR si !nuf', effect.call('Ruby is fun!') end def test_echo effect = Effects.echo(2) assert_equal 'RRuubbyy iiss ffuunn!!', effect.call('Ruby is fun!') effect = Effects.echo(3) assert_equal 'RRRuuubbbyyy iiisss fffuuunnn!!!', effect.call('Ruby is fun!') end end
感想
まあ、なんとなく使い方は分かった気がします。