【发布时间】: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"]
【问题讨论】: