Begging Ruby Chapter 1 Flashcards
What is object orientation
everything is an object guitar amps studio
Data Types
variable can hold these
Control Structures
variable can hold these
Is Ruby Open Source?
Yes
Ruby Interpreter
This is a ruby program that understands other programs written in the Ruby language, along with a collection of extensions and libraries to make your Ruby more fully featured
irb: Interactive Ruby
irb stands for “Interactive Ruby.” “Interactive” means that as soon as you type something, your computer will immediately attempt to process it. Sometimes this sort of environment is called an immediate or interactive environment.
object-oriented programming language
In the simplest sense, this means that your Ruby programs can define and operate upon concepts in a real-world fashion. Your program can contain concepts such as “people,” “boxes,” “tickets,” “maps,” or any other concept you want to work with. Object-oriented languages make it easy to implement these concepts in
a way that you can create objects based upon them. Object oriented languages can then act upon and understand the relationships between these concepts in any way you define.
nouns / verbs
Objects are nouns, methods are verbs.
3 corners of OOP
Encapsulation, Inheritance, Polymorphism
OOP
Style of programming where you create representations of “types” of objects like guitars and amps (Classes), and then can create specific objects like 69 strat, black les paul, 80s peavey, (instance of an object) that intend to use with each other.
attr_accessor
attr stands for “attribute,” and accessor roughly means “make these attributes accessible to be set and changed at will.”
print vs puts
puts automatically moves the output cursor to the next line
what can a ruby variable contain
numbers, text, and other data structures
class
A class is the definition of a single type of object
standard attribute syntax
attr_accessor :name, :age, :gender
what does inheritance allow you to do
Inheritance allows different classes to relate to one another and group concepts by their similarities
classless method
def guitar_strum
puts “brrriiing”
end
guitar_strum
Class
Class: A class is a definition of a concept in an object-oriented language such as Ruby. We created classes called Pet, Dog, Cat, Snake, and Person. Classes can inherit features from other classes, but still have unique features of their own.
Method
Method: A method represents a set of code (containing multiple commands and statements) within a class and/or an object. For example, our Dog class objects had a bark method that printed “Woof!” to the screen. Methods can also be directly linked to classes, as with fred = Person.new, where new is a method that creates a new object based upon the Person class. Methods can also accept data—known as arguments or parameters—included in parentheses after the method name, as with puts(“Test”).
Arguments/parameters
Arguments/parameters: These are the data passed to methods in parentheses (or, as
in some cases, following the method name without parentheses, as in puts “Test”). Technically, you pass arguments to methods, and methods receive parameters, but for pragmatic purposes, the terms are interchangeable.
Kernel
Some methods don’t require a class name to be usable, such as puts. These are usually built-in, common methods that don’t have an obvious connection to any classes. Many of these methods are included in Ruby’s Kernel module, a module that provides functions that work from anywhere within Ruby code without being explicitly referred to.
Experimentation
One of the most fulfilling things about programming is that you can turn your dreams into reality. The amount of skill you need varies with your dreams, but generally if you want to develop a certain type of application or service, you can give it a try. Most software comes from necessity or a dream, so keeping your eyes and ears open for things you might want to develop is important. It’s even more important when you first get practical knowledge of a new language, as you are while reading this book. If an idea crosses your mind, break it down into the smallest components that you can represent as Ruby classes and see if you can put together the building blocks with the Ruby you’ve learned so far. Your programming skills can only improve with practice.
simple do if syntax
age = 10
puts “You’re too young to use this system” if age
string literal
When a string is embedded directly into code, using quotation marks as earlier, the con- struction is called a string literal. This differs from a string whose data comes from a remote source, such as a user typing in text, a file, or the Internet. Any text that’s pre-embedded within a program is a string literal.
interpolation
interpolation refers to the process of inserting the result of an expression into a string literal “#{x+y}”
“Test” + “Test”
TestTest
“Test”.capitalize
Test
“Test”.downcase
test
“Test”.chop
Tes
“Test”.next
Tesu
“Test”.reverse
tseT
“Test”.sum
416
“Test”.swapcase
tEST
“Test”.upcase
TEST
“Test”.upcase.reverse
TSET
“Test”.upcase.reverse.next
TSEU
regular expression (string)
A regular expression, therefore, is a string that describes a pattern for matching elements in other strings.
basic substitution
puts “yo la tango”.sub(‘tango’, ‘mango’)
regular expression
puts “foobar”.sub(‘bar’, ‘foo’)
regular expression substitution of first two characters syntax
x.sub(/^../, ‘Hello’)
iterate through a string and have access to each section of it separately
“xyz”.scan (/./) { |character| puts character }
any alphanumeric character or an underscore
\w
regular expression argument general syntax
(/something/)
Anchor for the beginning of a line
Anchor for the end of a line
$
Anchor for the start of a string
\A
Anchor for the end of a string
\Z
Any character
.
Any letter, digit, or underscore
\w
Anything that \w doesn’t match
\W
Any digit
\d
Anything that \d doesn’t match (non-digits)
\D
Whitespace (spaces, tabs, newlines, and so on)
\s
Non-whitespace (any visible character)
\S
scanning for each character but adding them together to make a word
.scan (/.+/)
scan for vowels syntax
“This is a test”.scan(/[aeiou]/) { |x| puts x }
matching operator
=~
array to string syntax
x.join(‘ ‘)
turning a string into an array syntax
“Words with lots of spaces”.split(/\s+/)
basic hash iteration syntax
x.each { |key, value| something happens here with each }
ternary operator
2 > 1 ? “yes” : “no”
ternary syntax
2 > 1 ? “yes” : “no”
x y
Comparison; returns 0 if x and y are equal, 1 if x is higher, and -1 if y is higher
turn beginning two elements of array into string with dash
array.first(2).join(“-“)
discarding hash elements
x.delete(key)
discard hash conditional example
hash_name.delete_if { |key, value| value
fruit case example
fruit = "orange" color = case fruit when "orange" "orange" when "apple" "green" when "banana" "yellow" else "unknown" end
code block
essentially an anonymous, nameless method or function
[{} or do end]
how to turn letters a through z into an array
(‘A’..’Z’).to_a
hash basic syntax
s = { :key => ‘value’ }
Variable
A placeholder that can hold an object—from numbers, to text, to arrays, to objects of your own creation.
Operator
Something that’s used in an expression to manipulate objects such as +(plus), - (minus), * (multiply), and / (divide). You can also use operators to do comparisons, such as with , and &&.
Integer
A whole number, such as 5 or 923737.
Float
A number with a decimal portion, such as 1.0 or 3.141592.
Character
A single letter, digit, unit of space, or typographic symbol.
String
A collection of characters such as Hello, world! or Ruby is cool.
Constant
A variable with a fixed value. Constant variable names begin with a capital letter.
Iterator
A special method such as each, upto, or times that steps through a list element by element. This process is called iteration, and each, upto, and times are iterator methods.
Interpolation
The mixing of expressions into strings.
Array
A collection of objects or values with a defined, regular order.
• Hash
A collection of objects or values associated with keys. A key can be used to find its respective value inside a hash, but items inside a hash have no specific order. It’s a lookup table, much like the index of a book or a dictionary.
Regular expression
A way to describe patterns in text that can be matched and compared against.
Flow control
The process of managing which sections of code to execute based on certain conditions and states.
Code block
A section of code, often used as an argument to an iterator method, that has no discrete name and that is not a method itself, but that can be called and handled by a method that receives it as an argument. Code blocks can also be stored in variables as objects of the Proc class (or as lambdas).
Range
The representation for an entire range of values between a start point and an endpoint.
Symbol
A unique reference defined by a string prefixed with a colon (for example, :blue or :name). Symbols don’t contain values as variables do, but can be used to maintain a consistent reference within code. They can be considered as identifiers or constants that stand alone in what they abstractly represent.
. .
including
. . .
not including
how would you check if letters a through z has r in it
(‘a’..’z’).include?(‘r’)
create a new triangle
Triangle.new(1,2,3)
what is the benefit of inheritence?
classes lower down the hierarchy get the features of those higher up, but can also add specific features of their own
what is the escape charecter
backslash \
print first 3 letters of “string”
p “string”[0..2]
how to create a lambda
l = lambda { “Do or do not” }
puts l.call
increase of all menu items by 10%
menu_items = {:curry => 4, :roti => 6}
menu_items.each do |item, price|
menu_times[item] = price * 1.1
end
.count
.count(argument) goes through an array and counts how many time argument appears
Select random elements from an array
def random_select(array, n)
result = []
n.times do
result
newest hash syntax
{ k: v }
how to spell initialize
Init i alize
summing elements in an array
inject(0) { |sum, num| sum + num }
syntax for simple do if w/ two conditionals
do if condition1 == true && condition2 == true
do using unless
do unless conditional1==true
not equal to comparison operator
!=
how to loop from n to m
n.upto(m) { code to loop }
how to code loop from m down to n
m.downto(n) { code to loop }
0 to 50 in 5 steps
0.step(50, 5) { code to loop }
using string delimiters
x =
result of “abc” * 5
abcabcabcabcabc
basic interpolation
”#{something}”
define regular expression
a search query
how to iterate through a string
‘string’.scan(/./){ |char| do something }
returning a string with no spaces
“this is a crazy sentence 123”.scan(/\S+/).join
matching operator
=~
.scan vs .match
.scan goes though everything, . match returns one match value
method to check if array has no elements
array.empty?
does an array have an element
array.include?(ImptArrgument)
methods for array and hash
.delete .delete_if .first .collect .each
methods for array
.first .first(arg) .last .last(arg) .reverse
hash methods
.size .each .keys .values .delete .delete_if .first
how to create a new hash which saves changed old hash
new_hash = {}; old_hash.each { |key,val| new_hash[key] = val + something }
demonstration of a class method
class Thing def self.thing_method puts "hello from class method" end
%w{ this is a long sentence }
[ “this”, “is”, “a”, “long”, “sentence” ]
%q{ this is a long sentence }
” this is a long sentence “
.collect
Returns a new array with the results of running block once for every element in enum.