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?

Ludisposed
11.8k2 gold badges41 silver badges91 bronze badges
asked Nov 17, 2017 at 17:23
\$\endgroup\$

2 Answers 2

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.
answered Nov 18, 2017 at 15:14
\$\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
    
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
answered Nov 18, 2017 at 15:18
\$\endgroup\$
2
  • 1
    \$\begingroup\$ As select! modifies the array in-place, it's actually the opposite of copying the values. \$\endgroup\$ Commented 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\$ Commented Nov 18, 2017 at 17:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.