Open edytawrobel opened 7 years ago
sequences of characters
[ ] Replace multiple characters in a string
"hello".tr('el', 'ip') #=> "hippo"
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"
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" |
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 |
use a block | [0, 2, 4, 6, 8] |
if _boolean_ elsif ... else ... end
unless _boolean_ ... else ... end
Case
ternary operator
or operator (if y x =y else x=z end)
or qual unless x x=y end
Basic methods
Look something up by its value => use index:
Count frequencies of a word:
.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
x += 2 (x = x +2)
200.next => 201
1234.class => Fixnum
123456789567.class => Bignum
-200.abs => 200
10.0.class => Float
3.333.round => 3
3.564.round => 4
3.564.floor => 3 (round down)
3.564.ceil => 4 (round up)
.upto
.downto
95.upto(100) { |num| print num, " " }
=> 95 96 97 98 99 100
a label that's being used to identify a piece of data
stored in memory once (:test.object_id)
to pass a message around between different parts of a program
1..10 - inclusive
1...10 - exclusive
(1..9).class => Range
.begin, .end, .first, .last, .include?
*
- splat operator, use to spread out the content of a range in an array
part of the language construct
a lot like variables, but they stay the same
TEST = 2 / Test = 2
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
traversing a fixed set of data. You know where the starting point and the ending point is.
times
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
a block of code that we want to be executed each time through the loop, each iteration and that block of code is defined between the do and the end for multiline block, or by the curly braces {}
think of them as a way of bundling up a set of instructions for use elsewhere
x = 1
array = [1, 2, 3, 4, 5]
array.each {|num| puts num * 20 + x}
=> 21, 41, 61, 81, 101
value1 <=> value2
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) |
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)
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]
testing framework (Ruby Specification)
spec - an executable example that tests whether a portion of code exhibits the expected behaviour in a controlled context
user story:
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
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
Proc objects are self-contained code sequences that you can create, store, pass around as method arguments, and execute with the call method.
a proc is an object whose job is to provide execution access to a previously defined code block
think of a proc as a "saved" block: just like you can give a bit of code a name and turn it into a method, you can name a block (blocks can't be saved to variables and don't have all the powers and abilities of a real object) and turn it into a proc. Procs are great for keeping code DRY. With blocks, you have to write your code out each time you need it; with a proc, you write your code once and can use it many times.
multiples_of_3 = Proc.new do |n|
n % 3 == 0
end
(1..100).to_a.select(&multiples_of_3)
&
is used to convert the proc into a block. We'll do this any time we pass a proc to a method that expects a block.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.
=> DAVID BLACK
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"]
a piece of code that carries its context around with it
they preserve the partial running state of a program
the classic example is a counter(the proc serves as a counter; it increments its variable every time it’s called):
Procs differ from methods in that they don’t care whether they get the right number of arguments. If too many arguments passed, they are ignored. You can also sponge them up into a single arg (*):
=> [] => [1] => [1,2]
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!"
=> “Still here!”
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]
lambda checks the number of arguments passed to it, while a proc does not. This means that a lambda will throw an error when passed the wrong number of arguments, whereas a proc will ignore unexpected arguments and assign nil to any that are missing.
when a lambda returns, it passes control back to the calling method; when a proc returns, it does so immediately, without going back to the calling method.
=> Batman will win!
Iron Man will win!
nil
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
@
it is attached to the instance of the class
class Car
def initialize(make, model)
@make = make
@model = model
end
end
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:
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
Ruby handles unacceptable behaviour at runtime by raising an exception.
You can handle exceptions—deal with the problem and keep the program running—by means of the rescue keyword. Rescuing involves a rescue block, which is delimited with the begin and end keywords and has a rescue clause in the middle
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
class InvalidLineError < StandardError
end
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
separation of concerns assigning specific tasks to separate methods and making your program less redundant and your code more reusable
splat arguments are preceded by a *, which signals we don't know how many arguments there are about to be, but it could be more than one
def what_up(greeting, *bros)
bros.each { |bro| puts "#{greeting}, #{bro}!" }
end
what_up("What up", "Justin", "Ben", "Kevin Sorbo")
algorithms well-defined sequences of steps
the combined comparison operator <=>
: returns 0 if the first operand equals the second, 1 if first operand is greater than the second, and -1 if the first operand is less than the second.
Along with false, nil is one of two non-true values in Ruby. Every other object is regarded as "truthy," meaning that if you were to typeif 2
or if "bacon"
, the code in that if statement would be run.
Inheritance is the process by which one class takes on the attributes and methods of another, and it's used to express an is-a relationship You can directly access the attributes or methods of a superclass with Ruby's built-in super
keyword.
class DerivedClass < Base
def some_method
super(optional args)
# code
end
end
end
ternary conditional expression takes three arguments: a boolean, an expression to evaluate if the boolean is true, and an expression to evaluate if the boolean is false: puts 3 < 4 ? "3 is less than 4!" : "3 is not less than 4."
the case statement:
case language
when "JS" then puts "Websites!"
when "Python" then puts "Science!"
when "Ruby" then puts "Web apps!"
else puts "I don't know!"
end
conditional assignment operator:||=
. It's made up of the or (||) logical operator and the normal = assignment operator. Use when we want to assign a variable if it hasn't already been assigned
yield methods that accept blocks have a way of transferring control from the calling method to the block and back again. We can build this into the methods we define by using the yield keyword.
Table of Content