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

前端 未结 6 1823
一向
一向 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:39

    What you're storing in your array is the result of calling your methods, not the methods themselves.

    def test1
      puts "foo!"
    end
    
    def test2
      puts "bar!"
    end
    

    You can store references to the actual methods like this:

    > arr = [method(:test1), method(:test2)]
    # => [#, #] 
    

    Later, you can call the referenced methods like this:

    > arr.each {|m| m.call }
    foo!
    bar!
    

提交回复
热议问题