What is the most efficient way to initialize a Class in Ruby with different parameters and default values?

后端 未结 7 1340
遇见更好的自我
遇见更好的自我 2020-12-23 11:59

I would like to have a class and some attributes which you can either set during initialization or use its default value.

class Fruit
  attr_accessor :color,         


        
7条回答
  •  别那么骄傲
    2020-12-23 12:26

    I like vonconrad's answer but would have a separate defaults method. Maybe it's not efficient in terms of lines of code, but it's more intention-revealing and involves less cognitive overhead, and less cognitive overhead means more efficient dev onboarding.

    class Fruit
      attr_accessor :color, :type
    
      def initialize(args={})
        options = defaults.merge(args)
    
        @color = options.fetch(:color)
        @type  = options.fetch(:type)
      end
    
      def defaults
        {
          color: 'green',
          type:  'pear'
        }
      end
    end
    
    apple = Fruit.new(:color => 'red', :type => 'apple')
    

提交回复
热议问题