Skip to content

Instantly share code, notes, and snippets.

@elof
Last active December 19, 2015 00:58
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 elof/5871973 to your computer and use it in GitHub Desktop.
Save elof/5871973 to your computer and use it in GitHub Desktop.

Hashes

What happens if you callh[:lolcats] on an empty hash?

It will return nil (and you'll give co-workers the giggles) Create a hash using a literal and another using new

Option A

my_hash = {}

Option B

my_other_hash = Hash.new() How to assign keys to and values in hash?

hash = { foo: corge, bar: grault, baz: qux } How to clear a hash?

hash_name.clear What are synonyms for the term hash?

object dict (dictionary) map (hashmap) key-value pair associative array T/F Do objects have key-value pairs?

T

Given a hash, how do you print out all the keys?

hash.keys()

Given a hash, how do you print out all the values?

hash.values()

Methods

What is the difference between functions and methods?

Methods are intrinsically bound to an object (self, @, etc).

They have direct access to the object's instance variables.

Define a function that accepts an income and tax_percentage and prints tax_due.

def todo end Can you test a function that prints to the screen using a function?

Not really. Kinda sorta, but no. puts and co are just for debugging.

Define a function that converts income and tax_percentage and returns tax_due.

Test it.

How do you define an optional parameter for a function?

def increment(a, b=1) return a + b end Create a method a prints 1-100

def sequence(a, b) for x in (a..b) puts x end end

sequence(1, 100) How would you permanently reverse an array?

Using reverse! will reverse it in place whereas reverse will return a reversed copy.

a.reverse! What would you expect the output be from the program (think about scope)?

def method(a,b) return a + b chicken = 1 + 3 end puts method(1,3) puts chicken 4 error Classes

Identify one instance object in the code below:

images << Image.new(items)

answer: images.first

What does this Class do?

class Song attr_reader :name, :artist, :duration end

aSong = Song.new("Bicylops", "Fleck", 260) aSong.artist # => "Fleck" aSong.name # => "Bicylops" aSong.duration # => 260 It creates a new instance of the Class Song which is "Bicylops" by the artist Fleck and is 260 seconds long.

Variables that start with 2 '@" symbols, are what kind of variable?

A class or "static" variable. For example, a Person class could keep track of the number of @@persons instantiated.

What do classes contain / encapsulate?

...

How do define a Class method vs an instance method?

...

How do you access classes (and modules) from a different file?

require './filename.rb' Find descendants of an instance object

(this is a bit advanced, don't worry about it)

class Parent def self.descendants ObjectSpace.each_object(Class).select { |klass| klass < self } end end Instance Variables

person = Person.new("AJ") person.name() Note that .name is an accessor, not direct access to the instance variable @name

class Person def initialize(name) @name = name names = name.split(" ") @first_name = names.first @last_name = names.last end

def name() return "#{@first_name} #{@last_name}" end end What happens to the variable names when the instantiation is complete?

It gets thrown away.

Why doesn't person.name give access to @name?

Methods

Creating a method with arguments:

syntax:

def method_name (var_1=value1, var_2=value2) expression... end def talk_about_programming(arg0="Ruby", arg1="Perl") return "#{arg0} is better than #{arg1}... and your father smelt of elderberries"
end

puts test("JavaScript", "Ruby") puts test() Give an example of daisychaining methods

"Hello World".downcase().reverse().upcase() How to create a method to add 3 parameters and return a sum

def addsum( a,b,c) puts a + b + c end

addsum(3,5,6) How to create a method to say: Hello ?

def hello(name) puts "hello " + name end

hello("travis") iterators

Give an example of an iterator that uses .each

syntax:

collection.each do |variable| code that operates the variable end arr = [1,2,3,4,5] arr.each do |i| puts(i) end Demonstrate how the .map iterator works.

array = [1, 2, 3, 4] array.map { |a| 2*a } # => [2, 4, 6, 8]
How can you change the array that map is operating on permanently?

array.map! { |a| 2 * 2} Explain in plain english what "iterate" means?

going through each part of a container

What are two ways to iterate in ruby? Which method is preferred?

Using a loop (for, loop, while, until, etc) or a method (.each, .map, .inject, etc).

.each is preferred.

Strings

How would you create a reversed copy of a string?

string.reverse()

How to make each word in a string lowercase?

string.downcase()

How to split a string it a string at each .?

string.split(".")

What are two ways for creating a string?

a = String.new("Hello World") a = "Hello World" Differences between "double-quote" and 'single quote':

Double quotes allow for hashstache templating

variable = [2,3,4] puts "this is something in your #{variable}" Types

Name the following types:

10 10.0 "ten" ["ten"] {ten: 10} {"ten" => 10} [:ten] fixnum float string array hash hash array What is the type of each object?

2 "Hello, San Francisco!" 1..100 [1, 2, 77, "si se puede"] { font_size: 10, font_family: "Arial" } answers

2.class # => Number "Hello, San Francisco!".class # => String 1..100.class # => Range [1, 2, 77, "si se puede"].class # => Array { font_size: 10, font_family: "Arial" }.class # => Hash How can you find the the class of Class?

"hello".class What do you expect to see from the following puts "ha! " * 3?

"ha! ha! ha! " What do you expect to see from the following codes puts 5 * "hahaha"?

error! you can multiply a number by a string! What do you expect to see from the following codes Array.is_a? Array

false Array is an instance of a Class. An instance of an Array is an Array instance.

Create a array of 10 random numbers. Iterate over that array to multiply each number by 3 and print out only the numbers that are divisable by 4

Print out a string saying "Hi (name), you are (age) years old, and you live in (city)"

person = { name: "AJ", age: 27, city: "San Francisco" } Create a new hash called my_favorites to include a user's favorite movie and food (ask if they like mexican or chinese better).

Prompt the user for this info and save to the hash. Use boolean on hash values to reply to their choice of liking Mexican or Chinese food better.

Variables

Store [1, 2] as a variable

x = [1, 2] What is the variable(s) in the following?

thing = "is Sparta" Arrays

What's wrong with this Array?

[ how, many, chucks, can, a, woodchuck, chuck?, 0420] [ "how", "many", "chucks", "can", "a", "woodchuck", "chuck?", 042] Split "99 bottles of beer on a wall" into an array of words and store it as a variable

Looks something like:

delicious = [99, "bottles", "of", "beer", "on", "a", "wall"] Variables

Local - ex: name Instance ex: @image Literal ex: 4 Constant ex: CA_SF_TAX = 8.8 Static (class) ex: @@number_of_instances Global ex: $badidea # NEVER use globals!!!! Hash

Correct the following

name => :lior == name: "lior" { :name => "lior" } == { name: "lior" } Show that the fat arrow and json-esque style of writing hashes are equivalent.

{ :name => "lior" } == { name: "lior" } Strings

Write the following using a hashstache instead of concatonation

return first_name} + " " + last_name "#{first_name} #{last_name}" Loops

Use for to iterate over a hash to create this array [[:link, "http://lior.jpg"], [:name, "lior"], [:dog, "alfonso"]]

array = []
hash = {link: "http://lior.jpg", name: "lior", dog: "alfonso"}
for key, value in hash do array << [key, value]
end
use while to print "0,1,2,3,4,5"

x = 0 while x <= 5 do
puts x x += 1 end Use for ... in to print out 1,2,3,4,5,6,7,8,9,10

for x in 1..10 { puts x } Arrays

what are the awesome array methods that would make my life way easier?

array.any? do to see if any of the elements meet a given condition and

array.all? do if all entries in an array meet a given condition

how do I extract certain kinds of values from an array?

Syntax

when is a block iterator construction preferable to an each.do construction?

do ... end is preferable when the block must span multiple lines or there is no argument (no |x|).

{ |x, y| ... } is preferable when the block looks good on a single line and there is are arguments.

What's the difference between a block, hash, hashrocket, fat arrow, and hashstache?

Aside from both using mustaches, they're completely different.

A block is more like a function that can be passed to a function. It can also be expressed in the do |x| ... end format.

A hashstache is a template inside of a string

name = "AJ" "Hi, my name is #{name}!" A hashrocket is used in documentation to denote the value of a variable

name = "AJ" name.reverse().downcase() name # => "ja" A fat arrow is syntax used for hashes where the keys are not symbols

{ name: "AJ" } #=> uses symbol as key { "name" => "AJ" } #=> uses string as key What are the uses of curly braces in Ruby?

Hash delimiters Code block delimiters String templates (hashstaches) What is the literal equivalent of h = Hash.new()?

{} Bash

Create a file named foo.rb, rename it bar.rb, and then remove it?

touch ./foo.rb mv ./foo.rb ./bar.rb rm ./bar.rb What are the two methods of using shebang?

The wrong way

#!/usr/bin/ruby The right way

#!/usr/bin/env ruby Why should you shebang env instead of ruby directly?

Using env will work with rvm and custom installations.

Calling ruby directly will invoke the system installed version, which may not be the correct version for the project at hand.

Networking

What ip address is always associated with localhost?

127.0.0.1

https://docs.google.com/a/elbeeventures.com/file/d/0B3RB7dcw4Z6TZzhMQzJGVG5uRXc/edit?usp=sharing

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