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

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

    If you don't want to override initialize then you'll have to move up the chain and override new. Here's an example:

    class Foo
      attr_accessor :bar, :baz
    
      def self.new(*args, &block)
        allocate.tap do |instance|
          if args.last.is_a?(Hash)
            args.last.each_pair do |k,v|
              instance.send "#{k}=", v
            end
          else
            instance.send :initialize, *args
          end
        end
      end
    
      def initialize(*args)
        puts "initialize called with #{args}"
      end
    end
    

    If the last thing you pass in is a Hash it will bypass initialize and call the setters immediately. If you pass anything else in it will call initialize with those arguments.

提交回复
热议问题