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

前端 未结 8 2121
清歌不尽
清歌不尽 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:29

    ok,

    I came up with a solution. It uses the initialize method but on the other hand do exactly what you want.

    class Test
      attr_accessor :name
    
      def initialize(init)
        init.each_pair do |key, val|
          instance_variable_set('@' + key.to_s, val)
        end
      end
    
      def display
        puts @name
      end
    
    end
    
    t = Test.new :name => 'hello'
    t.display
    

    happy ? :)


    Alternative solution using inheritance. Note, with this solution, you don't need to explicitly declare the attr_accessor!

    class CSharpStyle
      def initialize(init)
        init.each_pair do |key, val|
          instance_variable_set('@' + key.to_s, val)
          instance_eval "class << self; attr_accessor :#{key.to_s}; end"
        end
      end
    end
    
    class Test < CSharpStyle
      def initialize(arg1, arg2, *init)
        super(init.last)
      end
    end
    
    t = Test.new 'a val 1', 'a val 2', {:left => 'gauche', :right => 'droite'}
    puts "#{t.left} <=> #{t.right}"
    

提交回复
热议问题