Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding instance variable array's operators in Ruby

Sorry for the poor title, I don't really know what to call this.

I have something like this in Ruby:

class Test
  def initialize
    @my_array = []
  end
  attr_accessor :my_array
end
test = Test.new
test.my_array << "Hello, World!"

For the @my_array instance variable, I want to override the << operator so that I can first process whatever is being inserted to it. I've tried @my_array.<<(value) as a method in the class, but it didn't work.


2 Answers

I think you're looking for this:

class Test
  def initialize
    @myarray = []
    class << @myarray
      def <<(val)
        puts "adding #{val}" # or whatever it is you want to do first
        super(val)
      end
    end
  end
  attr_accessor :myarray
end

There's a good article about this and related topics at Understanding Ruby Singleton Classes.

like image 101
glenn mcdonald Avatar answered May 25 '26 07:05

glenn mcdonald


I'm not sure that's actually something you can do directly.

You can try creating a derived class from Array, implementing your functionality, like:

class MyCustomArray < Array
  def initialize &process_append
    @process_append = &process_append
  end
  def << value
    raise MyCustomArrayError unless @process_append.call value
    super.<< value
  end
end

class Test
  def initialize
    @my_array = MyCustomArray.new
  end
  attr_accessor :my_array
end
like image 44
yfeldblum Avatar answered May 25 '26 07:05

yfeldblum