Ruby class initialization

Viewed 3690

I want to create an object that can be initialized in two different ways. I found 3 different way's of accomplishing the same thing, I want to know which of my methods is the best one, and if there is another better way of doing it.

Method

attr_accessor :id, :status, :dateTime
  def initialize *args
    if args.length == 1
      puts args[0]
    @id = args[0]['id']
    @status = args[0]['status']
    @dateTime = args[0]['dateTime']
    else
      @id = args[0]
      @status = args[1]
      @dateTime = args[2]
    end
  end

Method 2: (note that I need to set the parameters by hand on this one as second way)

  attr_accessor :id, :status, :dateTime
  def initialize hash = nil
    if hash != nil
    @id = hash['id']
      @status = hash['status']
      @dateTime = hash['dateTime']
    end
  end

Method 3: (note that I need to set the parameters by hand on this one as second way AND that it is almost the same as my second way, just not in the constructor)

attr_accessor :id, :status, :dateTime
  def initialize
  end

  def self.create hash
    if hash != nil
      obj = Obj3.new
      obj.id = hash['id']
      obj.status = hash['status']
      obj.dateTime = hash['dateTime']
      return obj
    end
  end

Thanks in advance!

1 Answers
Related