# Copying and filtering Ruby arrays

I'm doing a Ruby exercise to create new arrays with a given filter.

Copy the values less than 4 in the array stored in the source variable into the array in the destination variable.

The editorial solution code is:

def array_copy(source)
destination = []
for number in source
# Add number to destination if number
# is less than 4
destination << number if number < 4
end
return destination
end


But, as a beginner, I came up with this solution:

def array_copy(source)
return source.select {|i| i < 4}
end


Is there any problems with my solution?

I think your answer is perfectly valid and much better than the editorial solution.

I only have two suggestions to improve it further:

• variable name i is commonly used for array indexes. Using it instead for array values can confuse the reader of the code.
• return is not needed - Ruby functions will implicitly return the value of the last evaluated expression.

I don't think you have any problems, but you can improve it:

1. In Ruby, you don't need to return explicitly:

def array_copy(source)
source.select {|i| i < 4}
end

2. The exercise says copy the values, so you might prefer using select!:

def array_copy(source)
source.select! {|i| i < 4}
end

• As select! modifies the array in-place, it's actually the opposite of copying the values. – Rene Saarsoo Nov 18 '17 at 16:41
• I understood it as replacing the current values rather than creating a new duplicate. That’s why recommended bang version. 😊 – ogirginc Nov 18 '17 at 17:50