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

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

    There is a general way of doing complex object initialization by passing a block with necessary actions. This block is evaluated in the context of the object to be initialized, so you have an easy access to all instance variables and methods.

    Continuing your example, we can define this generic initializer:

    class Test
      attr_accessor :name
    
      def initialize(&block)
        instance_eval(&block)
      end 
    end
    

    and then pass it the appropriate code block:

    t = Test.new { @name = 'name' }
    

    or

    t = Test.new do
      self.name = 'name'
      # Any other initialization code, if needed.
    end
    

    Note that this approach does not require adding much complexity to the initialize method, per se.

提交回复
热议问题