I have a custom class and want to be able to override the assignment operator.
Here is an example:
class MyArray < Array
attr_accessor :direction
def initialize
@direction = :forward
end
end
class History
def initialize
@strategy = MyArray.new
end
def strategy=(strategy, direction = :forward)
@strategy << strategy
@strategy.direction = direction
end
end
This currently doesn’t work as intended. upon using
h = History.new
h.strategy = :mystrategy, :backward
[:mystrategy, :backward] gets assigned to the strategy variable and the direction variable remains :forward.
The important part is that I want to be able to assign a standard value to the direction parameter.
Any clues to make this work are highly appreciated.
Due to the syntax sugar of methods whose names end in
=, the only way that you can actually pass multiple parameters to the method is to bypass the syntax sugar and usesend……in which case you might as well just use a normal method with better names:
However, you could rewrite your method to automatically un-array the values if you knew that an array is never legal for the parameter:
This seems like a gross hack to me, however. I would use a non-assigment method name with multiple arguments if you need them.
An alternative suggestion: if the only directions are
:forwardand:backwardwhat about: