Ruby class Array interactive
→ Click to get an interactive sample (type in code)
! → Has also a bang method (modifies self)
( ) → Optional argument
Creating
# arr = [1,'b',:dig]
Methods
Creating an Array
Querying
Comparing
Fetching
Assigning
concatarr.concat([3, :cat]) # [1,'b',:dig,3,:cat] Documentation Playground
[1, "b", :dig, "dog", :cat]replace .initialize_copyarr.replace(['fox','cat']) # ['cat','rat'] Documentation Playground
["fox", "cat", "bee"]append (alias push)arr.append(:bee,3) # [1,'b',:dig,:bee,3] Documentation Playground
[1, "b", :dig, :bee, 3]prepend (alias unshift)arr.prepend(:bee,3) # [:bee,3,1,'b',:dig] Documentation Playground
[:bee, 3, 1, "b", :dig]! See non-bang methods for:
flatten! reverse! rotate! shuffle! sort!
Deleting
! See non-bang methods for:
compact! reject! select!→(alias filter!) slice!→(see []) uniq!
Combining
product[1].product([2,3,7]) # [[1,2],[1,3],[1,7]] Documentation Playground
[[0, 2], [0, 3], [1, 2], [1, 3]]Iterating
combination[1,2,3].combination(2){|c|p c} # [1,2][1,3]… Documentation Playground
[1, 2, 3]; [[1, 2], [1, 3], [2, 3]]cycle(count|FOREVER)[0,1].cycle(2){|c|p c} # 0;1;0;1 Documentation Playground
nil; [1, 2, 3, 1, 2, 3]permutation[0,1].permutation(2){|c|p c} # [0,1];[1.0] Documentation Playground
[0, 1, 2]; [0, 1][0, 2][1, 0][1, 2][2, 0][2, 1]repeated_combination[0,1].repeated_combination(1){…} # [0,0]… Documentation Playground
[0, 1, 2]; [0, 0][0, 1][0, 2][1, 1][1, 2][2, 2]repeated_permutation[0,1].repeated_permutation(1){…} # [0,0]… Documentation Playground
[0, 1, 2]; [0, 0][0, 1][0, 2][1, 0][1, 1][1, 2][2, 0][2, 1][2, 2]reverse_each[0,1].reverse_each(1){|c|p c} # [0];[1] Documentation Playground
[0, 1, 2]; [0, 0][0, 1][0, 2][1, 1][1, 2][2, 2]Converting
map (alias collect)arr.map{|e| e.class} # [Int…,String,Symbol] Documentation Playground
[Integer, String, Symbol]! See non-bang methods for:
map!→(alias collect!)