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

前端 未结 8 2081
清歌不尽
清歌不尽 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}"
    
    0 讨论(0)
  • 2021-01-01 16:33

    As mentioned by others, the easiest way to do this would be to define an initialize method. If you don't want to do that, you could make your class inherit from Struct.

    class Test < Struct.new(:name)
    end
    

    So now:

    >> t = Test.new("Some Test Object")
    => #<struct Test name="Some Test Object">
    >> t.name
    => "Some Test Object"
    
    0 讨论(0)
提交回复
热议问题