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

后端 未结 7 1328
遇见更好的自我
遇见更好的自我 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:36

    More simple way:

    class Fruit
      attr_accessor :color, :type
      def initialize(color = 'green', type = 'pear')
        @color = color
        @type = type
      end
      def to_s
        "#{color} #{type}"
      end
    end
    
    
    puts Fruit.new # prints: green pear
    puts Fruit.new('red','apple') # prints: red apple
    puts Fruit.new(nil,'pomegranate') # prints: green pomegranate
    

提交回复
热议问题