array_cheat_sheet_reading.
md 12/12/2019
Array Cheat Sheet
Here is a quick reference for the methods and operations we learned in the previous lectures!
Manipulation
# add element(s) to the end using push
people = ["Tommy", "Bex"]
p [Link]("Maurice", "Abby") # prints ["Tommy", "Bex", "Maurice",
"Abby"]
p people # prints ["Tommy", "Bex", "Maurice",
"Abby"]
# remove the last element using pop
people = ["Tommy", "Bex"]
p [Link]() # prints "Bex"
p people # prints ["Tommy"]
# add elements(s) to the front using unshift
people = ["Tommy", "Bex"]
p [Link]("Oscar", "Matthias") # prints ["Oscar", "Matthias",
"Tommy", "Bex"]
p people # prints ["Oscar", "Matthias",
"Tommy", "Bex"]
# remove the first element using shift
people = ["Tommy", "Bex"]
p [Link]() # prints "Tommy"
p people # prints ["Bex"]
Checking Existence
# check if an element exists in an array using include?
people = ["Tommy", "Bex", "Abby", "Maurice"]
p [Link]?("Abby") # prints true
p [Link]?("Mashu") # prints false
# find the index of an element in an array using index
people = ["Tommy", "Bex", "Abby", "Maurice"]
p [Link]("Abby") # prints 2
p [Link]("Maurice") # prints 3
p [Link]("Oscar") # prints nil
p [Link]("Danny") # prints nil
String <> Array
1/2
array_cheat_sheet_reading.md 12/12/2019
# convert a string into an array using split
sentence = "Hey Programmers! What's up."
p [Link](" ") # prints ["Hey", "Programmers!", "What's",
"up."]
p [Link]("a") # prints ["Hey Progr", "mmers! Wh", "t's up."]
p [Link]("gram") # prints ["Hey Pro", "mers! What's up."]
p sentence # prints "Hey Programmers! What's up."
# convert an array into a string using join
words = ["Rubies", "are", "red"]
p [Link](" ") # prints "Rubies are red"
p [Link]("-") # prints "Rubies-are-red"
p [Link]("HI") # prints "RubiesHIareHIred"
p words # prints ["Rubies", "are", "red"]
2/2