Ruby: methods as array elements - how do they work?

前端 未结 6 1827
一向
一向 2021-02-19 05:58

This probably isn\'t something you should try at home, but for some reason or another I tried to create an array of methods in Ruby.

I started by defining two methods.

6条回答
  •  甜味超标
    2021-02-19 06:41

    @alestanis explained the reason well. If you were trying to store the methods, then you can do what Lars Haugseth says or you could do the folllowing:

    test1 = Proc.new { puts "test!" }
    test2 = Proc.new { puts "test2!" }
    a = [test1, test2]
    

    This may make your code much more readable.

    Here is an irb run.

    1.9.3p194 :009 > test1 = Proc.new { puts "test!" }
     => # 
    1.9.3p194 :010 > test2 = Proc.new { puts "test2!" }
     => # 
    1.9.3p194 :011 > a = [test1, test2]
     => [#, #] 
    

提交回复
热议问题