2
\$\begingroup\$

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?

\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
1
\$\begingroup\$

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
    
\$\endgroup\$
  • 1
    \$\begingroup\$ As select! modifies the array in-place, it's actually the opposite of copying the values. \$\endgroup\$ – Rene Saarsoo Nov 18 '17 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 Nov 18 '17 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.