Search code examples
rubyarraysblock

Ruby blocks within an array


I need an array of blocks, where each block can take an argument:

array = [
  block do |x| puts x end,
  block do |x| puts x.to_s+" - " end
]

and make a request in the form of:

array[0] << 34

I had an idea to convert large numbers into words. I was wondering about the limits of blocks. There may be another way of doing it, but I am curious if this is possible.


Solution

  • You can use lambdas:

    array = [ lambda { |x| puts x }, lambda { |x| puts "#{x} - " } ]
    
    array[0].call(34) # prints 34
    

    If you need to use the << operator to invoke the Proc, then you can create a class and overload it:

    class Foo
        def initialize( &proc )
            @proc = proc
        end
        def <<( input )
            @proc.call( input )
        end
    end
    
    array = [
        Foo.new { |x| puts x },
        Foo.new { |x| puts "#{x} - " } ]
    
    array[0] << 34 # prints 34