Search code examples
rubycastingjrubydata-transfer-objects

Array to Virtual Object


Problem!

I was wondering if it is possible for an array to be transfered into a virtual object via method. Let's say that I have a class "Person" with two properties "@name" and "@lastname" and then I have an array containing this information, so What I need is to pass each array item into a new object from Person's class.

Example #

class Person
  attr_accessor :name, :lastname
  def initialize(name = "", lastname = "")
    @name = name
    @lastname = lastname
  end
end

array_of_names = [["lucia", "germes"], ["eder", "quiñones"], ["pedro", "infante"]]
array_of_names.each_with_index do |item, index|
  virtual_object = item.to_vo(Person.new)
  virtual_object.inspect
  # => "#<Person:0x0000FF @name="eder" @lastname="quiñones">
end

Question?

Is this even possible by extending Array's class?

class Array
  def to_vo(object)
    # ...
    # ...
    # ...
  end
end

Any help would be highly appreciated

~ Eder Quiñones


Solution

  • Yes

    class Array
      def to_vo klass
        klass.new *self
      end
      # ..OR..
      def to_person
        Person.new *self
      end
    end
    
    p a.map { |e| e.to_vo Person }
    p a.map(&:to_person)