Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Arrays
# Array#reverse_each
# Just like Array#each, but reversed.
# This saves having to reverse an array if trying to iterate from the end
a = [1, 2, 3, 4]
str = ""
a.reverse_each{ |n| str += n.to_s } # str => "4321"
# Array.new
# This has some powerful extra features and some potential dangers
# For example, we can pass to a block to create an array populated with elements
# calculated from their respective indicies
Array.new(4){ |index| index * 2 + 1 } # => [1, 3, 5, 7]
# But be careful!
arr = Array.new(2, Hash.new) # => [{}, {}]
arr[0]['name'] = 'bob'
arr # => [{"name" => "bob"}, {"name" => "bob"}]
# The above example creates an array with each element referencing THE SAME hash.
# If you want multiple hashes, you must pass a block
arr = Array.new(2) { Hash.new }
arr[0]['name'] = 'bob'
arr # => [{"name"=>"bob"}, {}]
# Array#clear
# Clears all elements from array
arr = [1, 2, 3]
arr.clear
arr # => []
# Array#map in conjunction with Enumerable#with_index
arr = [1, 2, 3]
arr_new = arr.map.with_index { |element, index| element * index }
arr_new # => [0, 2, 6]
# passing an offset argument to with_index
arr_new = arr.map.with_index(2) { |element, index| element * index }
arr_new # => [2, 6, 12]
# I'm still trying to fully understand how Enumerable objects work, but here is the gist:
# arr.map creates and Enumerable object. The with_index function is a method of the
# Enumerable class, so we can call this on arr.map.
# When Enumerable#with_index is called on arr.map, it wraps the enumerable object returned
# by arr.map in a second enumerable object, specified by an index.
# This then allows the index and elements to be accessed by the following block. I'm still
# trying to work out the details about how this actually works under the hood
# Array#flatten
# Flattens multidimensional arrays
arr = [1, 2, [3, 4, 5], [1, 3]]
arr.flatten # => [1, 2, 3, 4, 5, 1, 3]
# Flatten also has a destructive twin: Array#flatten!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.