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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With