How can one set property values when initializing an object in Ruby?

前端 未结 8 2122
清歌不尽
清歌不尽 2021-01-01 16:09

Given the following class:

class Test
  attr_accessor :name
end

When I create the object, I want to do the following:

t = Test         


        
8条回答
  •  鱼传尺愫
    2021-01-01 16:16

    Would need to subclass Test (here shown with own method and initializer) e.g.:

    class Test
      attr_accessor :name, :some_var
    
      def initialize some_var
        @some_var = some_var
      end
    
      def some_function
        "#{some_var} calculation by #{name}"
      end
    end
    
    class SubClassedTest < Test
      def initialize some_var, attrbs
        attrbs.each_pair do |k,v|
          instance_variable_set('@' + k.to_s, v)
        end
        super(some_var)
      end
    end
    
    tester = SubClassedTest.new "some", name: "james"
    puts tester.some_function
    

    outputs: some calculation by james

提交回复
热议问题