Search code examples
ruby-on-railsrubyblockproc

Can I pass an array and a block as a parameter?


Currently learning to create blocks and my own version of Array methods. I was wondering if I could pass an array and a block as parameters to a method. Below is the code I am working on and it should be self-explanatory in what it should do but I keep getting an error. Especially with the method call and where I pass the block.

def mapper(arr, &prc)
  new_array = []
  arr.length.times do |i|
    new_array << prc.call(arr[i])
  end
  new_array
end

mapper([1,2,3,4], {|i| i * 2})

Solution

  • You can do it by passing the block outside the parentheses (adjacent to the method call):

    p mapper([1, 2, 3, 4]) { |index| index * 2 }
    # [2, 4, 6, 8]
    

    Otherwise it'll result in a syntax error. Ruby won't know where the block is being passed.

    As a side note, you can also define only the array as a needed argument, and then yield the block being passed:

    def mapper(arr)
      arr.size.times.map do |i|
        yield(arr[i])
      end
    end
    
    p mapper([1, 2, 3, 4]) { |index| index * 2 }
    # [2, 4, 6, 8]