rubymap-functionruby-block

Pass a block to map function


I was wondering if something like this was possible?

info = arrange_info({|x| [x.name, x.number]}, info_array)

def arrange_info(block, info)
    info.map(block).to_h
end

This would allow me to pass different blocks to arrange the array is different ways, how I have it now doesn't work, but is something like this possible?


Solution

  • A block can be passed as a method argument, but it needs to be the last one. You also cannot call a method before it has been defined :

    def arrange_info(info, &block)
      info.map(&block).to_h
    end
    
    info = arrange_info(info_array){|x| [x.name, x.number]}
    

    Here's a small test :

    class X
      def initialize(name, number)
        @name = name
        @number = number
      end
    
      attr_reader :name, :number
    end
    
    def arrange_info(info, &block)
      info.map(&block).to_h
    end
    
    info_array = [X.new('a', 1), X.new('b', 2)]
    
    p info = arrange_info(info_array) { |x| [x.name, x.number] }
    #=> {"a"=>1, "b"=>2}