Ruby 3.4 Throws SyntaxError While Passing Block As Argument In Index.

In Ruby, block passing in index refers to the practice of passing a block as an argument to an array, particularly when accessing or modifying elements within an array.

Before

The []= method, commonly used for setting values in arrays, allows for block arguments, enabling dynamic and flexible manipulation of array elements based on specified conditions.

In Ruby, we can pass block as an argument in index but Prism parses it as SyntaxError.

Here is an example of passing block as an argument in index

numbers = []

even_block = Proc.new { |i| i.even? }

def numbers.[]=(*args, &block)
  self.concat(args.flatten)
end

numbers[&even_block] = 10      #=> [10]

numbers[&even_block] = 11, 12  #=> [10, 11, 12]

After

Ruby 3.4, Block passing as an argument is no longer allowed in index and it throws SyntaxError.

numbers = []

even_block = Proc.new { |i| i.even? }

def numbers.[]=(*args, &block)
  self.concat(args.flatten)
end

numbers[&even_block] = 10

#=> block arg given in index (SyntaxError)

Need help on your Ruby on Rails or React project?

Join Our Newsletter