Skip to content

Instantly share code, notes, and snippets.

@Polyrhythm
Created March 30, 2012 17:11
Show Gist options
  • Save Polyrhythm/2253023 to your computer and use it in GitHub Desktop.
Save Polyrhythm/2253023 to your computer and use it in GitHub Desktop.
Ruby Array Select example
# 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
@jumph4x
Copy link

jumph4x commented Mar 30, 2012

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. Does to_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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment