marcusshepp
5/24/2016 - 1:58 PM

Ruby 2 Arrays

Ruby 2 Arrays

## Arrays
# create an array and append to it.
(foo ||= []) << :element
# another version
foo = Array.new
foo.push("bar")
# iterate with item and index
foo.each_with_index do |item, index|
  puts item, index
end
# max / min
arr = ["a", "b", "c", "d", "e"]

puts arr.max
puts arr.min

def max (a,b)
  a>b ? a : b
end

puts arr.min_by { |x| x.length }
puts arr.max_by { |x| x.length }

## is "foo" in array
a = [1, 2, 3]
2.in? a # => true 
a.member? 1 # => true 


```
#each returns the original object it was called on because it's really used for its side effects and not what it returns
#each_with_index passes not just the current item but whatever position in the array it was located in.
#select returns a new object (e.g. array) filled with only those original items where the block you gave it returned true
#map returns a new array filled with whatever gets returned by the block each time it runs.
#any? returns true/false (see the question mark?) and answers the question, "do ANY of the elements in this object pass the test in my block?". If your block returns true on any time it runs, any? will return true.
#all? returns true/false and answers the question, "do ALL the elements of this object pass the test in my block?". Every time the block runs it must return true for this method to return true.
#none? returns true only if NONE of the elements in the object return true when the block is run.
#find returns the first item in your object for which the block returns true.

```

# flatten
s = [ 1, 2, 3 ]           #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ]   #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten(1)              #=> [1, 2, 3, [4, 5]]