Array Methods
Arrays come with dozens of handy built-in methods, like a Swiss army knife for lists. You can count, sort, reverse, and find things without writing the steps yourself.
In this page:
Syntax
array.sort
array.reverse
array.uniq
array.include?(value)
array.first
array.last
Array Methods
Ruby arrays have dozens of useful built-in methods beyond the basics, like .sort, .uniq, .include?, .sum, .min, .max, and .first/.last.
Most of these come from the Enumerable module that Array includes, so they're also available on other collection types like Hash and Range. Learning these built-ins is key to writing concise, idiomatic Ruby instead of manual loops.
Note:
Because Array includes Enumerable, methods like sum, min, and sort also work on any custom class that includes Enumerable.
Example: Array Methods
numbers = [5, 3, 8, 1, 9, 3]
puts numbers.sort.inspect
puts numbers.uniq.inspect
puts numbers.include?(8)
puts numbers.sum
puts numbers.max
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Calling
sortand expectingnumbersto change, when it returns a new array unless you usesort!. - Sorting an array with mixed types like numbers and strings, which raises
ArgumentError. - Using
include?with a wrong type, such asnumbers.include?("8"), which isfalse.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: