Skip to content

Instantly share code, notes, and snippets.

@pvdb
Created March 22, 2010 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pvdb/340405 to your computer and use it in GitHub Desktop.
Save pvdb/340405 to your computer and use it in GitHub Desktop.
# question asked on aardvark.com: http://vark.com/t/b27d66
# Is there a ruby function to find the shortest and longest string inside an array?
# (my array will only store a bunch of stirngs)
# Here's a snippet of Ruby code that should get you going...
>> %w{ foo bar blegga very-long-string }.sort { |a, b| a.length <=> b.length }.first
=> "foo"
>> %w{ foo bar blegga very-long-string }.sort { |a, b| a.length <=> b.length }.last
=> "very-long-string"
>> _
# A first alternative for the above...
>> %w{ foo bar blegga very-long-string }.sort_by { |x| x.length }.first
=> "foo"
>> %w{ foo bar blegga very-long-string }.sort_by { |x| x.length }.last
=> "very-long-string"
>> _
# A second alternative for the above...
>> %w{ foo bar blegga very-long-string }.min { |a, b| a.length <=> b.length }
=> "foo"
>> %w{ foo bar blegga very-long-string }.max { |a, b| a.length <=> b.length }
=> "very-long-string"
>>
# Another way completely for finding the longest string...
# (finding shortest string left as exercise for the reader ;-)
>> %w{ foo bar blegga very-long-string }.inject("") { |longest, string| (string.length > longest.length) ? string : longest }
=> "very-long-string"
>> _
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment