edytawrobel / makers

0 stars 0 forks source link

Ruby #5

Open edytawrobel opened 7 years ago

edytawrobel commented 7 years ago

Table of Content

  1. Variables
  2. Numbers
  3. String
  4. Array
  5. Hash
  6. Symbols
  7. Booleans
  8. Constants
  9. Conditionals
  10. Loops and Iterators
  11. Code Blocks
  12. Classes/Methods/Modules
  13. csv library
  14. Procs and Closures
  15. Lambda
  16. Threads
  17. Error handling
  18. Rspec
edytawrobel commented 7 years ago

String - characters that are strung together

screen shot 2016-12-03 at 21 55 41

screen shot 2016-12-03 at 21 56 44

method use
sentence.split(' ') break up sentence into single words
words.sort sorts words
words.shift prints the first word after shifting it off
words.pop prints the last word after popping it off
words.upcase "HELLO"
words.downcase "hello"
words.capitalize "Hello"
words.length 5
words.reverse "olleh"
edytawrobel commented 7 years ago

Array

an ordered integer- indexed collection of objects

class method use output
array.join(", ") returns string "1, 2, 3, 4, 5"
array.reverse reverses order [5, 4, 3, 2, 1]
array.delete_at()2 deletes el at index [5, 4, 2, 1]
array.delete(5) deletes specific elements [4, 2, 1]
array.sort sorts by the value [1, 2, 4]
array.push(5) or array << 5 adds element to the end [1, 2, 4, 5]
array.pop deletes last element [1, 2, 4]
array.shift deletes the first element [ 2, 4]
array.unshift(1) adds element in the 1st position [1, 2, 4]
array + [9, 10] adds specified elements [1, 2, 4, 9, 10]
array - [2, 4] deletes specified elements [1, 9, 10]
array - [9] adds specified elements [1, 10]
array.uniq removes duplicates
size/length return the size of an array => 5
names = Array.new(4, "mac") assign a value to each element macmacmacmac
screen shot 2016-12-02 at 12 04 12 use a block [0, 2, 4, 6, 8]
edytawrobel commented 7 years ago

Conditionals

  1. if _boolean_ elsif ... else ... end

screen shot 2016-12-10 at 13 03 02

  1. unless _boolean_ ... else ... end

  2. Case screen shot 2016-12-10 at 13 10 04

  3. ternary operator screen shot 2016-12-10 at 13 10 59

  4. or operator (if y x =y else x=z end) screen shot 2016-12-10 at 13 12 11

  5. or qual unless x x=y end screen shot 2016-12-10 at 13 15 41

edytawrobel commented 7 years ago

Hash

an unordered, object- indexed collection of objects ("hanging file folders", labels)

  1. Basic methods screen shot 2016-12-10 at 12 01 43

  2. Look something up by its value => use index:

screen shot 2016-12-10 at 11 44 38

  1. Iteration:

screen shot 2016-12-27 at 10 43 19

  1. Count frequencies of a word: screen shot 2016-12-27 at 11 31 16

  2. .each_key / .each_value:

my_hash = { one: 1, two: 2, three: 3 }

my_hash.each_key { |k| print k, " " }
# ==> one two three

my_hash.each_value { |v| print v, " " }
# ==> 1 2 3
edytawrobel commented 7 years ago

Variables

Scope Indicators

screen shot 2016-12-10 at 10 37 27

edytawrobel commented 7 years ago

Integers

x += 2 (x = x +2) 200.next => 201 1234.class => Fixnum 123456789567.class => Bignum -200.abs => 200

Floats

10.0.class => Float
3.333.round => 3
3.564.round => 4
3.564.floor => 3  (round down)
3.564.ceil => 4 (round up)

Ranges

.upto .downto

95.upto(100) { |num| print num, " " }
=> 95 96 97 98 99 100
edytawrobel commented 7 years ago

Symbols

screen shot 2016-12-10 at 12 20 54

edytawrobel commented 7 years ago

Booleans

Boolean Tables

screen shot 2016-12-01 at 19 22 10 screen shot 2016-12-01 at 19 22 39

Examples

screen shot 2016-12-10 at 12 36 14

edytawrobel commented 7 years ago

Ranges


1..10 - inclusive
1...10  - exclusive
(1..9).class     => Range

screen shot 2016-12-10 at 12 47 26

edytawrobel commented 7 years ago

Constants

edytawrobel commented 7 years ago

Loops

x = 0
loop do
  x += 2
  break if x >= 20
  puts x
end

2,4,6,8,10,12,14,16,18

x = 0
x += 2
  break if x >= 20
  next if x == 6
  puts x
end

2,4,8,10,12,14,16,18

x = 0
  while x < 20
  x += 2
  puts x
end

put x += 2 while x < 20

2,4,6,8,10,12,14,16,18,20

y = 3245
put y /= 2 until y <= 1

Iterators

5.times do
   puts "Coding is awesome!"
end

-

5.downto(1) {puts "hello"}
(1..5).each {puts "hello"}
1.upto(5) do |num|
   puts "Hello" + num.to_s
end

=> Hello1 Hello2 Hello3 Hello4 Hello5

fruits = ['apple', 'pear', 'banana']
fruits.each do |fruit|
   puts fruit.capitalize
end

=> Apple Pear Banana

screen shot 2016-12-02 at 11 06 21

screen shot 2016-12-02 at 11 04 14

edytawrobel commented 7 years ago

Code Block

x = 1
array = [1, 2, 3, 4, 5]
array.each {|num| puts num * 20 + x}

=> 21, 41, 61, 81, 101

e m a
-1 Less than moves "left"
0 Equal stays
1 More than moves "right"

Use it is to compare two values. Value one on one side, value two on the other. When it compares those, Comparison operator is going to return -1 if one thing is less than the other, 0 if they're the same, or return the value of 1 if value one is more than value two.

method use returns
find/detect (1..10).find { |i| i % 3 == 0 } => 3 Object or nil
find_all/select (1..10).select { |i| i % 3 == 0 } => [3, 6, 9] Array
any? / all? (1..10).any? { |i| i % 3 == 0 } => true Boolean
delete_if? [*1..10].delete.if { |i| i % 3 == 0 } => [1, 2, 4, 5, 7, 8, 10] Array with all the matching elements removed
merge h1.merge(h2) {|k, o, n|} o < n ? o : n {"a" => 111, "b" => 222, "c" => 444}
collect/map hash.map {|k, v|} "#{k}: #{v*20}" {"a: 2220", "b: 4440", "c => 6660"}
hash.sort (by keys) {|item1, item2} item1[0] <=> item2[0] [["a", 55], ["b", 22], ["c", 66]]
array.sort.reverse numbers.sort.reverse [5, 4, 3, 2, 1]
array.sort_by fruits.sort_by {|f| fruit.length} ['pear', 'apple', 'banana']
inject (1..10).inject { |memo, n | memo + n } 55 (accumulator)
edytawrobel commented 7 years ago

Methods

fruits = ['apple', 'banana', 'plum', 'pear']

def longest_words(words)
  longest_word = words.inject do |memo, word|
    memo.length > word.length ? memo : word
  end
  puts longest_word
end

longest_words(fruits)
def over_five?(value)
  return "Exactly 5" if value.to_i == 5
  if value.to_i > 5
    return "over 5"
  else
    return "under 5"
  end
end

puts over_file?(112/8)

screen shot 2016-12-10 at 21 02 01

def add_and_subtract(n1=0, n2=0)
  add = n1 + n2
  sub = n1 - n2
  return [add, sub]  #square brackets optional
end

result = add_and_subtract(2,2)
puts result[0]
puts result[1]
#double assignment
add, sub = add_and_subtract(8, 3)
=> [11, 5]
edytawrobel commented 7 years ago

Rspec

  1. given some context
  2. when some event occurs
  3. then I expect some outcome

screen shot 2016-12-15 at 12 31 42

describe 'Car' do  # a class Car

describe '.colors' do   #class method 
    it "returns an array of color names" do
       c = ['blue', 'black', 'red', 'green']
       expect(Car.colors).to match_array(c)
    end
end

screen shot 2016-12-15 at 14 05 25

Matchers

group use example
Equivalence x == 1 x.eql?(1) expect(x).to eq(1)
Truthiness true/false expect(1 < 2).to be (true)
Numeric-comparison comparing numbers expect(100).to be eq(100) expect(100).to be < = 100 expect(5).to be_between(3,5).inclusive expect(1..10).to cover(3)
Collection arrays array = [1,2,3] expect(array).to include(2,3) expect(array).to end_with(3) expect(array).not_to match_array([1,2])
Collection strings str = 'Lynda' expect(string).to include('Ly', 'da')
Collection hashes hash = {:city => 'Dallas', :state => 'TX'} expect(hash).to include(:city, :state) expect(hash).to include(:city => 'Dallas')
Observation how values change, watch for output expect { array << 1 }.to change(array, :empty?).from(true).to(false)
expect do
  bob.first_name = 'Robert'
  bob.last_name = 'Smith'
end.to change(bob :full_name).from('Bob Smith').to('Robert Smith')
end
edytawrobel commented 7 years ago

Procs

multiples_of_3 = Proc.new do |n|
  n % 3 == 0
end

(1..100).to_a.select(&multiples_of_3)
floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911]
round_down = Proc.new do |float|
    float.floor
end
ints = floats.collect(&round_down)

=> [1, 3, 0, 7, 11, 482]

You create a Proc object by instantiating the Proc class, including a code block: pr = Proc.new { puts "Inside a Proc's block" } - pr.call - => "Inside a Proc's block" The code block becomes the body of the proc; when you call the proc, the block you provided is executed.

screen shot 2016-12-19 at 16 48 12

=> DAVID BLACK

screen shot 2016-12-19 at 17 00 46

Got block as proc
Inside the block
=> nil
numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
strings_array = numbers_array.map(&:to_s)
=> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

Closure (a proc with the local variable bindings preserved)

edytawrobel commented 7 years ago

Lambda

def lambda_demo(a_lambda)
  puts "I'm the method!"
  a_lambda.call
end

lambda_demo(lambda { puts "I'm the lambda!" })
=>  "I'm the method!"
 "I'm the lambda!"

screen shot 2016-12-20 at 09 09 50

  1. Lambdas require explicit creation
  2. return keyword inside a lambda triggers an exit from the body of the lambda to the code context immediately containing the lambda. return inside a proc triggers a return from the method in which the proc is being executed: screen shot 2016-12-20 at 09 15 03 => “Still here!”
  3. lambda-flavored procs are fussy - don’t like being called with the wrong number of arguments.
strings = ["leonardo", "donatello", "raphael", "michaelangelo"]
symbolize = lambda { |name| name.to_sym }
symbols = strings.collect(&symbolize)

=>[:leonardo, :donatello, :raphael, :michaelangelo]
my_array = ["raindrops", :kettles, "whiskers", :mittens, :packages]
symbol_filter = lambda { |param| param.is_a? Symbol }
symbols = my_array.select(&symbol_filter)
=> [:kettles, :mittens, :packages]
edytawrobel commented 7 years ago

Threads - enable a lightweight concurrent programming

--

Ruby’s threads allow to do more than one thing at once in a program, through a form of time sharing: one thread executes one or more instructions and then passes control to the next thread, and so forth.

![screen shot 2016-12-20 at 09 48 28] (https://cloud.githubusercontent.com/assets/15351358/21345794/7db763f6-c699-11e6-9f63-10a349f779c7.png)

Starting the thread 
Outside the thread
t = Thread.new do
  puts ""Starting the thread" 
  sleep 1
  puts "At the end of the thread"
end

puts "Outside the thread" 
t.join
=> Starting the thread 
Outside the thread
At the end of the thread
edytawrobel commented 7 years ago

Classes

screen shot 2016-12-21 at 11 59 45

kitt = Car.new("Pontiac", "Trans Am")


- This tells Ruby that whenever it creates a Car, it has to have a make and model, and each instance of Car will have its own @make and @model.

- **Class variables**  instead of belonging to an instance of a class, they belong to the class itself 

| variable     | use        | example
| :------------- |:-------------:|:-------------:|
| global |  available everywhere | $manufacturer
| local |  available for certain methods |  var = "winter"
| class | members of certain class | @@files
|instance | only available to particular instances of a class | @username

- private vs public methods:

| method     | use        
| :------------- |:-------------:
| public |  accessible everywhere, default Ruby methods
| private |  private to the object where they are defined. You can only call these methods from other code inside the object. The method cannot be called with an explicit receiver. 

In order to access private information, we have to create public methods that know how to get it. This separates the _private implementation_ from the _public interface_

##Module
contains a set methods and constants. Similar to classes, only modules can't create instances and can't have subclasses. They're just used to store things and separate methods and constants into named spaces (**namespacing** see Math::PI and Circle::PI)

**the scope resolution operator**, the double colon, it tells Ruby where to look for a specific bit of code. If we say Math::PI, Ruby knows to look inside the Math module to get that PI.

- to use a module we have to bring it in explicitly by using _require_: `require 'date'`

- **mixin** mixing together the behaviors of a class and a module in order for a class to use a module's methods, _include_ the module: `include Math`

module Action def jump @distance = rand(4) + 2 puts "I jumped forward #{@distance} feet!" end end

class Rabbit include Action attr_reader :name def initialize(name) @name = name end end

class Cricket include Action attr_reader :name def initialize(name) @name = name end end

peter = Rabbit.new("Peter") jiminy = Cricket.new("Jiminy")

peter.jump jiminy.jump

=>I jumped forward 3 feet! I jumped forward 2 feet! nil


- Whereas _include_ mixes a module's methods in at the instance level (allowing instances of a particular class to use the methods), the **extend** keyword mixes a module's methods _at the class level._ This means that class itself can use the methods, as opposed to instances of the class:

ThePresent has a .now method that we'll extend to TheHereAnd

module ThePresent def now puts "It's #{Time.new.hour > 12 ? Time.new.hour - 12 : Time.new.hour}:#{Time.new.min} # {Time.new.hour > 12 ? 'PM' : 'AM'} (GMT)." end end

class TheHereAnd extend ThePresent end

TheHereAnd.now

edytawrobel commented 7 years ago

Error handling - exceptions

screen shot 2016-12-26 at 12 00 24

backtrace returns an array of strings representing the call stack at the time the exception was raised: method names, filenames, and line numbers, showing a full roadmap of the code that was executed along the way to the exception message returns the message string provided to raise

screen shot 2016-12-26 at 12 33 29

screen shot 2016-12-26 at 13 03 28

def line_from_file(filename, pattern) fh = File.open(filename) line = fh.gets raise InvalidLineError unless line.include?(pattern) return line rescue InvalidLineError puts "Invalid line!" raise ensure fh.close end

edytawrobel commented 7 years ago

Concepts

def what_up(greeting, *bros)
  bros.each { |bro| puts "#{greeting}, #{bro}!" }
end

what_up("What up", "Justin", "Ben", "Kevin Sorbo")