lith wrote:
I would like array1 to remain unchanged. It seems a little inefficient
to clone array1 every time some_method is called.
If your code is slow, it's not because of this use of clone. If your
code isn't, don't bother.
"Inefficient" can also refer to memory. If the array has 4 million
entries, to copy it 100 times might be considered inefficient in that
sense.
How about something like this:
class MyArray
include Enumerable
def MyArray.init(arr)
@@arr = arr
end
def initialize
@deleted = {}
end
def delete_at(i)
@deleted[i] = true
end
def each
@@arr.each_with_index do |elmt, i|
next if @deleted[i]
yield elmt
end
end
def get_arr
out =
@@arr.each_with_index do |elmt, i|
next if @deleted[i]
out << elmt
end
out
end
end
MyArray.init ["banana", "strawberry", "apple"]
data1 = MyArray.new
data2 = MyArray.new
data1.delete_at(0)
data2.delete_at(1)
p data1.get_arr
puts "------"
p data2.get_arr
puts
search1 = data1.select do |elmt|
elmt.length > 5
end
p search1
puts "Found apple." if data2.include? "apple"
--output:--
["strawberry", "apple"]
···
------
["banana", "apple"]
["strawberry"]
Found apple.
--
Posted via http://www.ruby-forum.com/\.