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

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

    You could do this.

    class Test
       def not_called_initialize(but_act_like_one)
            but_act_like_one.each_pair do |variable,value|
                instance_variable_set('@' + variable.to_s, value)
                class << self
                        self
                end.class_eval do
                        attr_accessor variable
                end
            end
       end
    end
    
    (t = Test.new).not_called_initialize :name => "Ashish", :age => 33
    puts t.name #=> Ashish
    puts t.age  #=> 33
    

    One advantage is that you don't even have to define your instance variables upfront using attr_accessor. You could pass all the instance variables you need through not_called_initialize method and let it create them besides defining the getters and setters.

提交回复
热议问题