【问题标题】:Iterate through an array of one class object and put those elements into an array belonging to another class object with Ruby. [duplicate]遍历一个类对象的数组,并将这些元素放入一个属于另一个类对象的数组中。 [复制]
【发布时间】:2026-01-05 16:35:01
【问题描述】:

假设我有两个类:

class One
  attr_reader :array
  def initialize(array)
    @array = array
  end
end

class Two < One
  attr_reader :array
  def initialize
    @array = []
  end
end

我现在实例化“One”类的一个对象和“Two”类的两个对象。

array = ["D","E"] 
a = One.new(array)
b = Two.new
c = Two.new

是否可以在 One 类中创建一个接受两个参数的方法,如果字符串存在于 One @array 中,则复制该元素并将该元素放入属于 Two 类的指定数组的数组中?

Example:

def place_string(element,location)
  if location == "b"
    take element, copy it and place it into @array in b
  elsif location == "c"
    take element, copy it and place it into @array in c
  end
end
a.place_string("D","b")
a.place_string("E","c")

Output:
  a.array = ["D","E"]
  b.array = ["D"]
  c.array = ["E"]

【问题讨论】:

    标签: ruby arrays class


    【解决方案1】:
    class One
      attr_reader :array
      def initialize(array=[])
        @array = array
      end
    
      def copy(element, location)
        if array.include? element
          location.array << element
        end
      end
    end
    
    class Two < One
    end
    
    array = ["D","E"] 
    a = One.new(array)
    b = Two.new
    c = Two.new
    
    a.copy("D", b)
    a.copy("NOT EXIST", b)
    b.array
    #=> ["D"]
    

    【讨论】:

      最近更新 更多