ruby: mass initializing instance variables

前端 未结 2 1757
-上瘾入骨i
-上瘾入骨i 2021-01-14 15:03

Is there an easy way to bulk assign instance variables

  def initialize(title: nil, label_left: nil, label_right: nil, color_set: nil)
    @title = title
            


        
2条回答
  •  日久生厌
    2021-01-14 15:42

    @tadman provided already an excellent answer to this, but here is one more: If you are willing to dispense with named parameters, you could do it like this:

    def initialize(*args)
      @title, @label_left, @label_right, @color_set, *nada = args
      fail "Too many arguments" unless nada.empty?
    end 
    

    [UPDATE: Fixed the code, according to the comment given by @sawa].

提交回复
热议问题