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

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

    The typical way to solve this problem is with a hash that has a default value. Ruby has a nice syntax for passing hash values, if the hash is the last parameter to a method.

    class Fruit
      attr_accessor :color, :type
    
      def initialize(params = {})
        @color = params.fetch(:color, 'green')
        @type = params.fetch(:type, 'pear')
      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
    

    A good overview is here: http://deepfall.blogspot.com/2008/08/named-parameters-in-ruby.html

提交回复
热议问题