In a completely contrived problem on exercism.io, I'm tasked to come up with a way to get the length/size of an array without using any enumerable methods.
I originally simply had:
arr = [1,3,4]
ctr = 0
while arr[ctr]
ctr += 1
end
ctr
The problem is that I can have arr = Array.new(5), which is [nil, nil, nil, nil, nil].
I've found two ways:
ctr = 0
loop do
element = arr.fetch(ctr) { 'outofbounds!' }
break if element == 'outofbounds!'
ctr += 1
end
ctr
I'd like to do it without using Array#fetch because index out of bounds is just likely looking at the known length (which again I'm trying to implement).
Another solution:
ctr = 0
copy = arr.dup
while copy != []
ctr += 1
copy.pop
end
ctr
This feels slightly right but == on Array first checks length then checks == on each element. I'm trying to implement length so stuck again.
Array#each?counterin your second code?