「初めてのRuby」の復習をexpectationsで(メソッド)
# -*- coding: utf-8 -*- require "rubygems" require "expectations" #7章 メソッド Expectations do #多値 expect 2 do def foo; return 1, 2, 3; end a, b, c = foo b end expect [1, 2, 3] do def foo; return 1, 2, 3; end foo end #クロージャ expect "121" do def counter cnt = 0 return Proc.new do cnt += 1 cnt.to_s end end str, cnt = "", counter str << cnt.call # 1 str << cnt.call # 2 str << counter.call # 1(新しいcounterは、また1からカウントする) str end #Proc -> ブロック expect 10 do proc = Proc.new do |sum, n| sum + n end [2,3,5].inject(0, &proc) # &で修飾し、引数リストの最後に渡す end end
Ruby1.8では、ブロックローカル変数の宣言構文は存在しないとのこと。(ブロック内が初出のローカル変数は、ブロックローカルになるけれど)
なのでRuby1.8では、
- 外部ローカル変数とブロック引数を用いない
- 外部で既出のローカル変数は、ブロック内外で共有される
を気に留めておくように・・・ということです。
ブロック内とローカル変数は、意識して違う名前つけましょう・・・と。