Skip to content

Instantly share code, notes, and snippets.

@jnewman12
Last active December 19, 2016 18:55
Show Gist options
  • Save jnewman12/446d379e9aa280c19b79bfa7cbef2749 to your computer and use it in GitHub Desktop.
Save jnewman12/446d379e9aa280c19b79bfa7cbef2749 to your computer and use it in GitHub Desktop.
Slides for ruby arrays, hashes, and blocks

Arrays, Hashes, & Blocks


Learning Objectives
Use basic array methods including count, first, and last
Iterate through arrays with each method
Use the appropriate data collection for a situation: hash vs. array
Get and set values for specific hash key
Get a list of all keys in a hash

Road Map

  1. Intro
  2. Working with Arrays
  3. Independent Practice
  4. Working with Hashes
  5. Independent Practice
  6. Conclusion

Intro

  • For these Ruby data collections, you'll be reminded of similar ideas in JS.
  • arrays are pretty much the same, as are objects, and blocks

Working with Arrays

  • what are arrays for? What do they do?
  • We make arrays in Ruby the same as we did in JS
nums = [1,2,3,4]

  • Then, once you've created an array, how do you imagine you add to an array?
nums.push(5)
# => [1,2,3,4,5]

  • Similarly, we've can "shovel" a value into the array.
nums << "not a num"
# => [1,2,3,4,5,"not a num"]

Removing From Arrays

  • As we see, it's possible to mix data types (Ruby does not care
  • So let's delete that from our array of numbers.
nums.delete "not a num" # give it the value you want to get rid of
# => [1,2,3,4,5]

Useful Array Methods

  • There are so many great array methods - here are a few you'll probably use often.

# how many sheep are there?
nums.length # => or nums.count

# just as you'd expect, get's the value at nth index. remember, and indexes start at 0!
nums[3] # => 4

# a handy method equivalent to sheep[0]
nums.first
# also a handy method equivalent to sheep[numbers.length-1]
nums.last

# and what if disorder put us to sleep?
nums = [3,2,4,1,5]

# But we'll need to wake up!
nums.sort # [1,2,3,4,5]
nums.sort.reverse # => [5, 4, 3, 2, 1]

Iteration

  • looping through our array and doing something with each value.
  • Remember iterating in JS using for loops?
  • We can do for loops in Ruby, too, but we've got something much nicer:
nums.each do |number|
  puts "i am number #{number}"
end

# i am number 1
# i am number 2
# i am number 3
# i am number 4
# i am number 5

  • In fact, many methods can iterate:
nums.count do |number|
  if number < 4
    puts "#{number}"
  else 
    puts "or nah"
  end
end

  • To find more useful array methods, you'll have to look in the Ruby Docs!

Blocks

  • That do/end is called a block, and it just runs the code in between, almost like a little function without a name - like anonymous functions in JavaScript .
  • You'll see blocks all the time, and you'll use .each like it's your job
  • It just loops through each value in your array and assigns a local variable (that you decide) to each object.
  • You come up with what you want it called in the "pipes" surrounding the variable:

|a_variable_of_my_choosing|


  • Think of these pipes as little slides that send the variable directly into your block.
# if nums is a variable holding [1, 2, 3, 4, 5], then nums.each will go through each number and o something to each variable
# nums.each do |number|
#   puts "i am num #{number}"
# end
# i am num 1
# i am num 2
# ... etc ...

  • For best practice, always name your |a_variable_of_my_choosing| something obvious.
  • Best practice is to use the singular tense of the array you're iterating over:
dreams.each do |dream|

or

values.each do |val|

  • Of course, the beauty of loops is that we don't have to write all that out.
  • you can also use curly brackets for a block, which is convenient for one liners
  • in ruby, it gives higher precedence to {} than do/end
nums.each do |num|
  puts "i am num #{num}"
end

nums.each {|num| puts "i am num #{num}"}

Methods

  • let's learn basic syntax in Ruby methods.
  • Much like Javascript functions, we can name our blocks as methods!
  • Unlike JS, we use the def keyword to define methods in Ruby, and end to close our block.
def count_num(nums)
  nums.count do |number|
    if number < 4
      puts "#{number}"
    else 
      puts "nope"
    end
  end
end

# To call the method:
count_num(nums)

  • Again, recall that parentheses are optional. We can now access count_num later in our program and pass any array!
nums = [1,2,3,4,5]
count_num(nums) # or count_num nums

# Will Print:
# "1"
# "2"
# "3"
# "nope"
# "nope"

Independent Practice

nums = [3, 0, 4, 15, 8, 11, 28, 1, 17]
  • Given the list of nums, iterate over them and add the numbers index of the array to the number. save numbers in a new array
  • sort the array of numbers by lowest to highest
  • Then, print out all the numbers in the array

Working with Hashes - Defining Our Reveries

  • We use hashes constantly. Hashes, like JS objects, are a great way to store related data of all different kinds, in a way that's super readable.
  • The key to hashes is that they always house key:value pairs. The key describes the properties, the value is the information relating to or describing the property.

Creating a Hash

To see it in action, let's pick something random in the room and try to describe it.

student = {
	class_taken: 'WDI',
	languages_learned: ['JS', 'Ruby', 'CSS'],
	tired: false,
	things: {
		:val_1 => 1,
		val_2: 2
	}
}

  • Now, based on what you know about how JS objects work, how would you guess we grab data out of here?
  • How would we grab our boolean value?
student[:tired] # => false

Symbols Are For Memory

  • In Ruby, keys, like those up above, are symbols, not strings.
  • Symbols are basically just like strings, except they save computer memory.
  • Every string you create is unique and takes up space on your computer, even if they're the same value! When we're busy looking up key/value pairs, we don't want to be wasting memory - we want it to be fast!

Let's watch:

"Your Name".object_id
#=> a number

"Your Name".object_id
#=> a different number

:your_name.object_id
#=> a number

:your_name.object_id
#=> the same number!

  • Symbols on their own don't do much, but they work great as keys. There are two ways to write them:
{
  # from older ruby versions, still totally work
  :the_old_way => 'some value',

  # from newer ruby versions, which is just shorter
  the_new_way: 'some value'
}

  • Either are fine; you'll see both a lot. It is recommended to go to the new syntax, but working with older code, you will see both
  • strings as keys are possible – we just try not to use them.

Adding to our hash

Real quick – what if we forgot a key/value pair, or want to add one in after the fact?

dream[:my_power] = 'righteous high-five'

# dream = {
#   type: 'super-powered',
#   friends: ["Superman", "The Big Fundamental", "Sonic the Hedgehog"],
#   monster_trucks: 7,
#   pants_on: true,
#   setting: {
#     environment: "deciduous",
#     music: 'Jimmy Buffet'
#   },
#   my_power: 'righteous high-five'
# }

Hash Removal

  • How do you think we'd remove a key:value pair?
  • Given we just learned to do this with arrays, it's okay to be unsurprised.
dream.delete :pants_on
# remember, parentheses are optional!

Independent Practice - Hash Out Your Dream

  • Now you try it!

  • Partner up! Together and by hand with markers on the desk, describe a dream as a hash. Use any data types you can think of, because hash values can be anything!

  • When you're done, each of you, independently open your computer, and write it out in Pry, terminal, repl. Try getting each key out, adding in new ones, and deleting ones just for fun.

  • In your hashes, try to:

    • Include one key value with the value as an array
    • Include one key value with the value as another hash (look to the fan hash from earlier!)

Conclusion

  • How do you get the 4th item of an array?
  • How do you get a value out of a hash?
  • How do you add a value to a hash? What about an array?

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