Created
March 22, 2010 19:07
-
-
Save pvdb/340405 to your computer and use it in GitHub Desktop.
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
# 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