A
Avi S g
I wrote a simple version of the collect method for the Array class
called my_collect. Here is what I wrote:
class Array
def my_collect
result = []
self.each {|element| result.push(yield(element))}
result
end
end
x = [1,2,3].my_collect {|element| element + 1}
print x
It prints out 234 correctly. However, I was puzzled by what x contained
if I removed the return value 'result', that is:
class Array
def my_collect
result = []
self.each {|element| result.push(yield(element))}
#Removed return value
end
end
x = [1,2,3].my_collect {|element| element + 1}
print x
It prints out 123. Why? The last evaluated expression would probably be
result.push(yield(3)), and since push returns the resulting array,
wouldn't it be 234 in this case as well?
Thanks,
FeralHound
called my_collect. Here is what I wrote:
class Array
def my_collect
result = []
self.each {|element| result.push(yield(element))}
result
end
end
x = [1,2,3].my_collect {|element| element + 1}
print x
It prints out 234 correctly. However, I was puzzled by what x contained
if I removed the return value 'result', that is:
class Array
def my_collect
result = []
self.each {|element| result.push(yield(element))}
#Removed return value
end
end
x = [1,2,3].my_collect {|element| element + 1}
print x
It prints out 123. Why? The last evaluated expression would probably be
result.push(yield(3)), and since push returns the resulting array,
wouldn't it be 234 in this case as well?
Thanks,
FeralHound