Seasons.NET

ちょっとした技術ブログです

__send__を使ってメソッドのシンボルからメソッドをコール

私は、lambdaでProcオブジェクトを生成して、callかと思っていたのですが、
__send__ってあるんですね。。。
リファレンスよく読めよ!!って感じですね・・・orz

 1 require 'pp'
 2 $KCODE = "S"
 3 
 4 def hoge
 5   p "hoge"
 6 end
 7 
 8 def hoge2
 9   p "hoge2"
10 end
11 
12 def callfunc( methods )
13   for i in 0...methods.size
14     __send__( methods[i] )
15   end
16 end
17 
18 def main
19 
20   # __send__を使うならこれ
21   methods = [:hoge,:hoge2]
22   callfunc( methods )
23 
24   # Lambdaを使うならこれ
25   methods = [lambda{p "hello"}]
26   methods[0].call
27 
28 end
29 
30 main()
31 
32