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 thedestination
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?
2 Answers 2
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:
In Ruby, you don't need to
return
explicitly:def array_copy(source) source.select {|i| i < 4} end
The exercise says copy the values, so you might prefer using
select!
:def array_copy(source) source.select! {|i| i < 4} end
-
1\$\begingroup\$ As
select!
modifies the array in-place, it's actually the opposite of copying the values. \$\endgroup\$Rene Saarsoo– Rene Saarsoo2017年11月18日 16:41:00 +00:00Commented Nov 18, 2017 at 16:41 -
\$\begingroup\$ I understood it as replacing the current values rather than creating a new duplicate. That’s why recommended bang version. 😊 \$\endgroup\$ogirginc– ogirginc2017年11月18日 17:50:34 +00:00Commented Nov 18, 2017 at 17:50
Explore related questions
See similar questions with these tags.