Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Ruby Index

📋 Array — Dynamic array — push, map, select, reduce

Ruby arrays are ordered, integer-indexed collections of any objects. They double as stacks, queues, and function as the basis for most data processing in Ruby.

📋 Methods & Functions

NameSignatureDescription
push / <<arr.push(obj) or arr << obj → arrAppend element
poparr.pop → objRemove and return last element
shiftarr.shift → objRemove and return first element
unshiftarr.unshift(obj) → arrPrepend element
first/lastarr.first(n) / arr.last(n)First/last n elements
length/sizearr.length → IntegerNumber of elements
empty?arr.empty? → boolTrue if array has no elements
include?arr.include?(obj) → boolTrue if array contains obj
flattenarr.flatten(depth) → ArrayReturn flattened copy
compactarr.compact → ArrayReturn copy without nil values
uniqarr.uniq → ArrayReturn copy with duplicates removed
sortarr.sort → ArrayReturn sorted copy
sort_byarr.sort_by {|e| key} → ArraySort by computed key
reversearr.reverse → ArrayReturn reversed copy
map/collectarr.map {|e| expr} → ArrayTransform each element
select/filterarr.select {|e| bool} → ArrayKeep matching elements
rejectarr.reject {|e| bool} → ArrayRemove matching elements
reduce/injectarr.reduce(init) {|acc,e| expr}Fold to single value
eacharr.each {|e| block} → arrIterate over elements
each_with_indexarr.each_with_index {|e,i| block}Iterate with index
flat_maparr.flat_map {|e| Array} → ArrayMap then flatten one level
ziparr.zip(other) → ArrayZip with another array
samplearr.sample(n) → obj/ArrayReturn random element(s)
shufflearr.shuffle → ArrayReturn randomly shuffled copy
min/maxarr.min / arr.max → objMinimum/maximum element
sumarr.sum → NumberSum all elements
countarr.count(obj) → IntegerCount occurrences
tallyarr.tally → HashCount occurrences of each element
any?arr.any? {|e| bool} → boolTrue if any element matches
all?arr.all? {|e| bool} → boolTrue if all elements match
none?arr.none? {|e| bool} → boolTrue if no elements match
group_byarr.group_by {|e| key} → HashGroup all elements by key
filter_maparr.filter_map {|e| expr_or_nil}Map and filter nils (Ruby 2.7+)
combinationarr.combination(n) → EnumeratorAll n-element combinations
permutationarr.permutation(n) → EnumeratorAll n-element permutations
intersection &arr & other → ArrayElements common to both
union |arr | other → ArrayAll unique elements from both
difference -arr - other → ArrayElements in arr not in other
rotatearr.rotate(n) → ArrayRotate elements left by n
each_slicearr.each_slice(n){|chunk| block}Iterate in chunks of n
each_consarr.each_cons(n){|window| block}Sliding window of n

💡 Example Program

Run with ruby script.rb.

# Array — Ruby's workhorse
nums = [5, 3, 8, 1, 9, 2, 7, 4, 6]
puts nums.sort.inspect
puts nums.select(&:odd?).inspect
puts nums.map { |n| n**2 }.inspect
puts nums.reduce(:+)
puts nums.min_by { |n| (n - 5).abs }

# Chaining
words = %w[banana apple cherry date elderberry fig]
result = words
  .select { |w| w.length > 4 }
  .map(&:capitalize)
  .sort
puts result.inspect

# tally
votes = %w[go ruby rust go java go ruby rust go]
puts votes.tally.sort_by { |_,v| -v }.inspect

# filter_map (Ruby 2.7+)
puts (1..10).filter_map { |n| n**2 if n.odd? }.inspect

# zip
names  = %w[Alice Bob Carol]
scores = [95, 87, 92]
names.zip(scores).each { |n,s| puts "#{n}: #{s}" }

# each_slice — process in batches
words.each_slice(2) { |batch| puts batch.inspect }

# Combinations
puts [1,2,3].combination(2).to_a.inspect
# ruby array_demo.rb

← String  |  🏠 Index  |  Hash →