A Ruby Cheatsheet For Arrays
A reference for beginners and forgetful professionals
Simply put, before you lies a metric ton of handy Ruby Array methods. It’s long, but I tried to include all the really useful stuff. When a method is used, be sure to check the docs for more info. And to keep things shorter, I’ll write return values in comments, so arr # -> "stuff"
means that the return value for arr
is “stuff”
.
Creating Arrays
Create a new, empty array: Array #new
arr = []
arr2 = Array.new
Create a new array with values:
arr_with_stuff = ["value", "separated by comma"]
arr_with_stuff2 = Array.new(["a", "b", "c"])
range_to_arr = (1..9).to_a
create an array of duplicate values: Sometimes it’s helpful to have an array filled with multiple, duplicates:
arr = Array.new(5, " ")
# -> [" ", " ", " ", " ", " "]
create an array of strings with a shortcut: use the %w
shortcut to create an array of strings without quotes or commas:
arr = %w(cat dog mouse 1 2)
# -> ["cat", "dog", "mouse", "1", "2"]
convert a string into an array: #split will split a string into an array. It takes an argument of a string to decide where to split the array items, otherwise it splits by space. To get each character alone, specify “”
as the argument:
arr = "this is a string”.split
arr # -> ["this", "is", "a", "string"] "hey".split("") # -> ["h","e","y"]
bonus: convert an array to a string: #join does the opposite and creates a new string from an array. It takes a string as an optional argument, which will be inserted between values:
arr = %w(cat dog mouse)
str = arr.join(", ")
str # -> "cat, dog, mouse"str2 = arr.join
str2 #-> "catdogmouse"
Reading/Getting Values
Get the length of the array: #length and #size are aliases
arr = %w(cat dog mouse cow pig)
arr.length # -> 5
arr.size # -> 5
Get the value at an index
arr[0] # -> "cat"
arr[1] # -> "dog"
arr[100] # -> nil