This entry will be about Arrays and Hashes in Ruby. I'll cover what these are, how to create new arrays and hashes, and some basic methods for each.
First off, what is are these things? Well, sometimes, you have to store some things in lists. In this case, an Array will store the list in an order, with a built-in numbered index (more on this in a second) which looks like this: [0,1,2,"three",4]
. A Hash will store things in a key: value pair. Like this: {"k1"=>"v1","k2"=>"v2"}
where k means key and v means value.
Arrays are basically like Hashes in that the value is the element you see, and the key is actually its index (position in the array). For example,
array = ["one", "two", "three"]
array[0] = "one"
Here, the index 0 is actually the first position. Important to note that the numbering indexes always starts with 0. Anyway, in this way, the "key" in an array is the index, and the "value" is the element at that index. A hash with the keys all numbered starting from 0 would return the same value if called. The point is, though, that hashes can be used to use a different key than just a numbered index.
Arrays
Creating Arrays
- Literal Constructor
array_name = []
- Can add any number of elements separated by commas.
array_name = Array.new
- Creates empty array.
array_name = Array.new(3)
creates an array with 3 "nil" elements.array_name = Array.new(3, "abc")
creates an array with three "abc" elements:["abc", "abc", "abc"]
array_name = Array.new(3){"abc"}
does the same thing.
- Array Method
- Converts what you've got into an array
- To check if these work, try
string.respond_to?(:to_ary)
orstring.respond_to?(:to_a)
.to_ary
(No strings!).to_a
(No strings!)Array(string)
yields[string]
Calling elements in an Array
array[i]
where i is an index (integer), gives the element at that index.array[i, n]
where i is an index and n is the number of elements to call. Ex:array = [3,4,5,6,7]
array[2,2]
=>5,6array[i, n] = a, b
will change the element at i with a, and the next element with b. n represents the number of elements to be changed.array.slice(a,b)
Returns element at index a. b is optional, it will return that number of elements starting with a..array.slice!(a,b)
Does the same as above, but changes the array to only include the elements returned.array.values_at(a, b, c...)
Gives the elements at the specified index a, b, c, etc.
Add and remove elements
array.unshift(0)
Will add 0 to beginning of array.array.push(0)
Will add 0 to the end of array. Can add more than one at a time.array <<0
Will add 0 to the end of array. Can NOT add more than one at a time.array.shift
Removes and prints 1st element.array.pop
Removes and prints last element.array.shift!
andarray.pop!
Performs action and permanently changes the array.
Combining Arrays
array1.concat(array2)
Adds elements of array2 to the end of array1 (destructive).array1 = array1 + array2
Adds elements of array1 and array2 into a new array (non-destructive).array1.replace(array2)
Replaces elements in array1 with elements of array2 (destructive).
Transform Array
array.flatten(n)
Removes n layers of nested arrays and puts their elements in the array. Without (n), it just removes all of the arrays nested, putting all of the elements in order.array.flatten!(n)
Does the same as above, but makes change permanent.array.reverse
andarray.reverse!
Reverses the positions of all elements in the array.array.join()
Combines elements into a string. The parameter could be(" ")
which will add a space between all of the elements.array * " "
Does the same as above.array.uniq
andarray.uniq!
Removes duplicated elements.array.compact
andarray.compact!
Removes nil elements.
Array Query
array.size
Gives number of elements.array.empty?
True if empty, false if not.array.include?(item)
True if item is there, false if not.array.count(item)
Gives number of times item is in the array.array.first(n)
Gives first n number of elements.array.last(n)
Gives last n number of elements.array.sample(n)
Gives n number of random elements.
Hashes
Creating Hashes
- Literal Constructor
h = {"k1"=>"v1", "k2"=>"v2", etc.}
- Can add any number of paired key/value pairs separated by commas.
h = Hash.new
- Creates empty hash.
h = Hash.new(3)
Sets default value at 3 for non-existant keysh.default(value)
Sets default value.h = Hash.new {|hash, key| hash[key]=0}
Makes it so if a nonexistant key is called, it will add that key to the hash with the default value of 0.
Hash.[]
Where [] includes an EVEN number elements, will order the pairs as key/value pairs, so 0=>1, 2=>3 and so on. Can also work with nested arrays.something.to_hash
Will turn that something, usually an array, into a hash. If the argument doesn't have to_hash as a method, fatal error occurs.
Adding to Hash
hash["new_key"] = "new_value"
Creates that key/value pair.hash.[]("new_key", "new_value")
Does the same, but the above is easier on the eyes, hence "syntactic sugar".hash.store("new_key", "new_value")
Does the same.- Keys must be unique or they'll be overwritten.
Calling in Hash
hash[key]
Gives the value to that key.hash.fetch(key)
Gives the value to that key.hash.values_at(key1, key2)
Gives value of each key in an array like this:[value1, value2]
Combining Hashes
h1.update(h2)
Adds h2's key/value pairs to h1. Overwrites duplicates.h3 = h1.merge(h2)
Creates new hash. Doesn't overwrite h1 if duplicated, but figures out which duplicate to keep.h1.merge!(h2)
Same as .update.
Select/Reject in Hashes
hash.select {|k,v| k > 1}
Will give you the k/v pairs where k is an integer greater than 1.hash.reject {|k,v| k > 1}
Does the opposite. Gives you the k/v pairs that DON'T have k > 1.hash.select!
andhash.reject!
will permanently change the hash with those parameters.
Transforming Hashes
hash.invert
Keys become values, values become keys. Duplicates will be overwritten.hash.clear
Empties the hash.hash.replace
Replaces the key in pair with the one provided.
Query in Hashes
hash.has_key(key)
True if key exists, False if not.hash.include?(key)
Same.hash.key?(key)
Same.hash.member?(key)
Same.hash.has_value(value)
True if value exists, False if not.hash.value?(value)
Same.hash.empty?
True if empty, False if not.hash.size
Gives number of pairs in hash.
Well, that's a lot! But hopefully will be helpful as a guide for myself and others in the future.