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 people.push("Maurice", "Abby") # prints ["Tommy", "Bex", "Maurice",
"Abby"]
p people # prints ["Tommy", "Bex", "Maurice",
"Abby"]
# remove the last element using pop
people = ["Tommy", "Bex"]
p people.pop() # prints "Bex"
p people # prints ["Tommy"]
# add elements(s) to the front using unshift
people = ["Tommy", "Bex"]
p people.unshift("Oscar", "Matthias") # prints ["Oscar", "Matthias",
"Tommy", "Bex"]
p people # prints ["Oscar", "Matthias",
"Tommy", "Bex"]
# remove the first element using shift
people = ["Tommy", "Bex"]
p people.shift() # prints "Tommy"
p people # prints ["Bex"]
Checking Existence
# check if an element exists in an array using include?
people = ["Tommy", "Bex", "Abby", "Maurice"]
p people.include?("Abby") # prints true
p people.include?("Mashu") # prints false
# find the index of an element in an array using index
people = ["Tommy", "Bex", "Abby", "Maurice"]
p people.index("Abby") # prints 2
p people.index("Maurice") # prints 3
p people.index("Oscar") # prints nil
p people.index("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 sentence.split(" ") # prints ["Hey", "Programmers!", "What's",
"up."]
p sentence.split("a") # prints ["Hey Progr", "mmers! Wh", "t's up."]
p sentence.split("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 words.join(" ") # prints "Rubies are red"
p words.join("-") # prints "Rubies-are-red"
p words.join("HI") # prints "RubiesHIareHIred"
p words # prints ["Rubies", "are", "red"]
2/2