What is the most efficient way to initialize a Cla

2019-01-31 03:48发布

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, :type
  def initialize(color, type)
    @color=color ||= 'green'
    @type=type ||='pear'
  end
end

apple=Fruit.new(red, apple)

标签: ruby oop class
7条回答
该账号已被封号
2楼-- · 2019-01-31 04:20

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')
查看更多
登录 后发表回答