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

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

    Since Ruby 2.0 there is support of named or keyword parameters.

    You may use:

    class Fruit
      attr_reader      :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(:color => 'red', :type => 'grape')) # prints: red grape
    puts(Fruit.new(:type => 'pomegranate')) # prints: green pomegranate
    

    Some interesting notes on this topic:

    • Keyword arguments in Ruby 2.0
    • Ruby 2.0.0 by Example
    • Named parameters in Ruby 2

提交回复
热议问题