Skip to content

Instantly share code, notes, and snippets.

@Elffers
Last active December 27, 2015 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Elffers/7306623 to your computer and use it in GitHub Desktop.
Save Elffers/7306623 to your computer and use it in GitHub Desktop.
Documentation on array and hash methods investigated by class

###Homework for 4 November 2013

####Array Method

  • delete_if

######Returns an array

Syntax: array.delete_if { | item | block }

Removes element from array if code block returns true.

Example 1: If you wish to remove all even numbers from an array:

my_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.delete_if {|number| number.even?} 

=> [1, 3, 5, 7, 9]

Example 2: If you wish to remove all names that are not capitalized:

names = ["Ada", "benjamin", "carl", "Dan", "Erastosthenes"]
names.delete_if { |name| name == name.downcase}

=> ["Ada", "Dan", "Erastosthenes"]

  • slice

######With one integer argument (index), returns value at that index. ######With two integer arguments(start, number_of_items), returns array with number_of_items elements starting at index (start) ######With one range argument (start_index..end_index), returns array of values from start index to end index, inclusive

#####Syntax: array.slice(index)

array.slice(start, number_of_items)
array.slice(start_index..end_index)

Example:

    array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    array.slice(5)

=> 6

    array.slice(3, 5)

=> [4, 5, 6, 7, 8]

    array.slice(3..5)

=> [4, 5, 6]

Hash Method

  • select

#####Syntax: hash.select { block }

Returns a new array with keys and values for which the code block returns true.

Example 1: If you wish to return all months that inclue the letter "y":

months = {:jan => "january", :feb =>"february", :mar =>"march", :apr =>"april", :may ==> "may",
 :jun => "june", :jul => "july", :aug => "august", :sep => "september", :oct => "october", 
 :nov =>"november", :dec => "december"}

months.select {|key, value| value.include? "y"}

=> {:jan=>"january", :feb=>"february", :may=>"may", :jul=>"july"}

**Example 2: **

blah = {1 => [1, 2, 3], 2 => [4, 8], 3 =>[7, 8, 9], 4 => [35, 31]}
blah.select { |key, value| key == value.length }

=> {2=>[4, 8], 3=>[7, 8, 9]}

  • flatten
Syntax: hash.flatten
hash.flatten(int) int = flattens number of times

Takes all keys and values and puts them into an array

@kerrizor
Copy link

kerrizor commented Nov 7, 2013

I love the multiple, real-world examples!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment