Created
March 30, 2012 17:11
-
-
Save Polyrhythm/2253023 to your computer and use it in GitHub Desktop.
Ruby Array Select example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Write a method named get_squares that takes an array of numbers | |
# and returns a sorted array containing only the numbers whose square is also in the array | |
# | |
# get_squares [9] # => [] | |
# get_squares [9,3] # => [3] | |
# get_squares [9,3,81] # => [3, 9] | |
# get_squares [25, 4, 9, 6, 50, 16, 5] # => [4, 5] | |
def get_squares(array) | |
to_return = array.select do |square| | |
square if array.include?(square * square) | |
end | |
to_return.sort | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works, avoid naming things
to_return
. Try to erase the context. You don't know what array is, you don't know what the method signature means. Doesto_return
still have any semantics attached? no so much.Also you need guard conditions. Any publicly facing methods should test for extrema. In this case, test to make sure array.is_a? Array