Sunday, April 10, 2016

Ruby_Lesson_Data Structures

More with Arrays
1.Creating Arrays
my_array = [1,2,3,4]
2.Access by Index
We can access the ith element of an array called array by putting the index in square brackets, like so: array[i]. array[0] gets the first element, array[1] gets the second element, and so on. This is called access by index.
demo_array = [100, 200, 300, 400, 500]
print demo_array[2]

3.Arrays of Non-Numbers
You can make an array of any collection of Ruby objects. You can make an array of booleans! An array of strings! The list is (almost) endless.
string_array = ["a","b","c"]
4.Arrays of Arrays
Arrays of arrays are called multidimensional arrays, since the act of adding more arrays expands the array out of its string-like shape. For instance, the array in the editor is a two-dimensional array.
multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
Hashes
6.Introduction to Hashes
Hashes are sort of like JavaScript objects or Python dictionaries.all you need to know that a hash is a collection of key-value pairs. Hash syntax looks like this:
hash = {
  key1 => value1,
  key2 => value2,
  key3 => value3
}
Values are assigned to keys using =>. You can use any Ruby object for a key or value.
my_hash = {
  "name" => "Eric",
  "age" => 26,
  "hungry?" => true
}
puts my_hash["name"]
puts my_hash["age"]
puts my_hash["hungry?"]

7.Using Hash.new
You can also create a hash using Hash.new, like so:
my_hash = Hash.new
Setting a variable equal to Hash.new creates a new, empty hash; it's the same as setting the variable equal to empty curly braces ({}).
pets = Hash.new
food = {}

8. Adding to a Hash
We can add to a hash two ways: if we created it using literal notation, we can simply add a new key-value pair directly between the curly braces. If we used Hash.new, we can add to the hash using bracket notation:
pets = Hash.new
pets["Stevie"] = "cat"
# Adds the key "Stevie" with the
# value "cat" to the hash
9.Accessing Hash Values
puts pets["Stevie"]
# will print "cat"
Iterating Over Arrays and Hashes
10.(Re)Introduction to Iteration
When we loop over an array or a hash, we say that we iterate over it.
friends = ["Milhouse", "Ralph", "Nelson", "Otto"]
family = { "Homer" => "dad",
  "Marge" => "mom",
  "Lisa" => "sister",
  "Maggie" => "sister",
  "Abe" => "grandpa",
  "Santa's Little Helper" => "dog"
}
friends.each { |x| puts "#{x}" }
family.each { |x, y| puts "#{x}: #{y}" }

12.Iterating Over Multidimensional Arrays
If we just wanted to access "swiss", we could type
s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

s[0][1]
Project
1.get input from the user.
puts "please input text"
text = gets.chomp

2.Declare a variable called words and set it equal to the result of calling .split on text.
words = text.split
3.Creating the Frequencies Hash
We'll want to make sure the hash has a default value.
h = Hash.new("nothing here")
puts h
# {}
puts h["kitty"]
# nothing here
  1. In the example above, we create a new, empty hash h that has a default value of "nothing here".
  2. Then we print out {}, the value of h, just to show that h really is empty.
  3. Then we print out nothing here as we try to access the value stored by the key "kitty".
If you have a hash with a default value, and you try to access a non-existent key, you get that default value.
frequencies = Hash.new(0)
4.Iterating Over the Array
Perfect! Next up: we want to iterate over words to add each word to our frequencies hash, one at a time.
colors = {"red" => 2, "blue" => 3}
colors["blue"] += 1
puts colors["blue"]
  1. In the above example, we first create a hash mapping strings to integers.
  2. Then, we increment the value stored by "blue" by 1.
  3. Finally, we print out 4, the value stored by "blue".
Use .each to iterate over the words array.
For each word we find, assume that the word itself is a key in frequencies and increment its
words.each{|word| frequencies[word]+=1}
5.Sorting the Hash
colors = {"blue" => 3, "green" => 1, "red" => 2}
colors = colors.sort_by do |color, count|
  count
end
colors.reverse!
  1. In the example above, we first create a hash called colors that maps color strings to numbers.
  2. Then, we sort colors into green, red, and blue, from smallest to largest by count. Just so you know, the .sort_by function returns an array of arrays, but that's fine for our purposes.
  3. Finally, we reverse the array order so that the colors with the largest counts are first.
frequencies = frequencies.sort_by do |word,num|
    num
end
frequencies.reverse!

6.Iterating Over the Hash
fruit = {
  "apple" => 2,
  "banana" => 3,
  "cherry" => 5
}

fruit.each do |name, count|
  puts name + " " + count.to_s
end
  1. In the example above, we create a hash called fruit that maps names of fruit to the amount that we own.
  2. Then, we iterate over .each key/value pair, storing the key as name and the value as count.
  3. Finally, we print out the key and value separated by a space. Note that we must first convert the value from a number to a string using .to_s before we can concatenate it.
    |word,num| puts word+" "+num.to_s







No comments :

Post a Comment