Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

ruby - Setter method (assignment) with multiple arguments

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 use send

h.send(:strategy=, :mystrategy, :backward )

…in which case you might as well just use a normal method with better names:

h.set_strategy :mystrategy, :backward

However, you could rewrite your method to automatically un-array the values if you knew that an array is never legal for the parameter:

def strategy=( value )
  if value.is_a?( Array )
    @strategy << value.first
    @strategy.direction = value.last
  else
    @strategy = value
  end
end

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 :forward and :backward what about:

def forward_strategy=( name )
  @strategy << name
  @strategy.direction = :forward
end

def reverse_strategy=( name )
  @strategy << name
  @strategy.direction = :backward
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...