假设我有两个班级:
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"]
答案 0 :(得分:2)
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"]