数组到虚拟对象

发布于 2024-11-10 17:07:22 字数 775 浏览 7 评论 0原文

问题!

我想知道是否可以通过方法将数组转移到虚拟对象中。假设我有一个类“Person”,它有两个属性“@name”和“@lastname”,然后我有一个包含此信息的数组,所以我需要的是将每个数组项传递到 Person 类中的一个新对象中。

示例 #

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

问题?

这是否可以通过扩展 Array 的类来实现?

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

任何帮助将不胜感激

〜Eder Quiñones

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽袖吟 2024-11-17 17:07:22

是的

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文