local
こんな感じの出力を返すらしい。
local(3) #===以下出力=== >1 >2 >3 >3 >2 >1
実装してみる
def local(depth) def out(n) puts(" "*(n-1) + ">#{n}") end 1.upto(depth) {|e| out e} depth.step(1,-1){|e| out e} end
ブロックも使ってみた
def local2(depth, &b) if b #if block_given? def out(n) yield(" "*(n-1)+">#{n}") end else def out(n) puts(" "*(n-1)+">#{n}") end end 1.upto(depth) {|e| out(e,&b)} depth.step(1,-1){|e| out(e,&b)} end local2(10) {|e| puts e} #メソッドの呼出し
local2メソッドのブロックは、実行時にprocオブジェクト変換されるため、
block_given?を使わず、単に「b ? true : false」(&bのとき)と書くこともできるみたい。
どっちがいいんだろ?