Ruby basics + advanced Flashcards
What is ruby?
It is a programming language
What does RVM stand for?
Ruby version manager
What does RVM let you do?
It lets you switch between different versions of ruby.
What are variables?
They are the building blocks of a program and they let you store information.
How much information can a variable store?
Variables can store a lot of data, full algoritms, blocks and lambdas
How do you set a variable in ruby?
you give it a name and set it equal to the information
ex variable_1 = ‘A string’
How can you print out objects to the terminal?
- puts
- p
What is puts?
puts will return nil and print out the object in a new line. Puts also iterates over the values.
What is p?
p will return the value and print out the object
How do you get user input form the terminal?
you use the gets method
What is chomp?
chomp deletes the extra character that your gets method adds to the input.
What kinds of variables are there?
- Local variables
- Global variables
- Instance variables
- Constants
- Class variables
What is a local variable?
A local variable is a variable that limits itself to a local scope of where it is declared.
It is only available to that specific method or package
What is a global variable?
A global variable written with a $ before the variable name is available all over the application. And it’s a terrible idea. because the last time you set the variable will declare it.
What is a instance variable?
An instance variable is written with a @ sign before the variable name.
The instance variable is available for that instance in other places.
What is a constant?
A constant is a variable is written with CAPITAL letters and is a variable that is not supposed to be changed.
What is a class variable?
A class variable is written with @@ is a variable that is available to that instance of the class.
What is a string?
A string is a object where you store a collection of characters. These must be contained in single or double quotes
What is string interpolation?
String interpolation is a method where you can display dynamic values inside a string. Everything between a #{ } will be embedded ruby. You must use double quotes on the string when working with string interpolation.
What is string manipulation?
String manipulation is when you use methods to change the strings.
what is a bang? ( ! )
When you see the ! in the end of a method it means that it is changing the original version of the variable .
What is string substitution?
String substitution is a method in ruby. You use .gsub!( ‘original’ , ‘the change’)
What is the strip method?
it removes the extra spaces in a string in the beginning and in the end of a string
What is the split method?
The split method converts each word in a string to an array.
What is the order of execution in ruby?
Please Excuse My Dear Aunt Sally =
Paranthesis, Exponents, Multiplication, Division, Addition, Subtraction
What is the difference between integers and floats?
A float has decimals and integer doesn’t.
make sure to use decimal to get the proper output.
What is the difference between floats and decimals?
Floats do not have many decimal points, but decimals can have a lot of numbers to be accurate.
How do you declare a method?
def snake_case
some logic
end
How do you call/run a method?
you just type the method name
What is the difference between puts and return
puts is used for debugging purposes and does not store a value.
return prints and stores the value and is used in production applications.
What is the difference between a class method and a instance method?
You can call the class method directly on the class But you need to create an instance to be able to call an instance method.
ex
SomeClass.some_class_method
ex
variable = Invoice.new
variable.some_instance_method
How do you write a class method?
you add self before the method name in a class method.
def self.method_name
something
end
How do you call a class with a class method
SomeClass.some_class_method
What are Procs?
Procs are blocks of code (methods) that can be stored inside variables.
How do you write a Proc?
ex
variable = Proc.new { |argument1, argument2 | some code }
or ex variable = Proc.new do | argument1, argument 2 | some code end
How do you call a Proc?
proc_variable[ argument1, argument2]
or
proc_variable.call(argument1, argument2)
How do write a lambda?
variable = lambda { |argument1, argument2 | some code }
or
variable = -> (argument1, argument2) { |argument1, argument2 | some code }
How do you call a lambda?
lambda_variable[ argument1, argument2]
or
lambda_variable.call(argument1, argument2)
What is the difference between a Proc and Lambda?
1 lambdas count the number of arguments given (you must give right number of arguments).
2 Procs do not count the arguments (Procs ignore excess arguments).
3 Procs and lambdas have return differences. Procs do not return everything but lambdas do
What are method arguments?
The method arguments are the raw material provided by the user.
What are named arguments?
It is when you need to name your arguments when calling them, good for readability, to avoid confusion and you can give arguments in random order.
ex def write_name(first_name: , last_name: ) puts first_name puts last_name end
write_name(first_name: “Faraz”, last_name: “Naeem”)
What are default arguments?
Default arguments are arguments that are already written in the method, so that you only need to write out the argument when you want to overwrite the argument in the method.
What is a splat argument?
A Splat argument allows you to pass in multiple arguments into a method but it treats the arguments like an array.
ex
def method(*players)
some_code
end
method(argument1, argument2, argument3, argument4 …)
What is a keyword based splat argument?
a keyword based splat argument allows you to pass in an hash, then the
def method(**players)
some_code
end
method(some_hash)
What are optional arguments?
Optional arguments allows you to use arguments that you specifically want, and it will ignore other.
ex
def method_name(options ={})
puts [:some_key]
end
method_name(some_key: “hej”, another_key: “då”)
=> hej
What is a while loop?
It is a bit of code that will run as long as the conditions are true, it is very important to increment the value otherwise the loop will run forever.
while i < 10
puts “hey”
i += 1
end
What is the each loop?
the each loop is an iterator.
ex
variable.each do |value|
some_code for value
end
ex
variable.each { |value| some code for value}
What is the for loop?
the for loop executes code once for each element in expression.
ex
for i in 0..4
puts i
end
ex
for variable [, variable …] in expression [do]
code
end
What is an nested iterator?
It is when you are iterating on a collection inside another collection. (two hashes inside one hash)
ex
hash.each do | main_hash_value, sub_hash | puts main_hash_value sub_hash.each do |key, value| some code end end
What is the select method?
The select method selects a value from a collection and runs your code.
ex
(1..10).to_a.select do |value|
value.even?
end
ex
(1..10).to_a.select { |value| value.even? }
ex
(1..10).to_a.select(&:even?)
What is the map method?
The map method takes an enumerable object and a block and runs the block for each object.
ex
array.map { |value| value.some_method }
ex
array.map(&:some_method)
What is the inject method?
The inject method is used to combine number (addition subtraction, multiplication and so on)
ex array.inject(&:+) ex array.inject(&:-) ex array.inject(&:*)
How do you create an array?
ex
x = [1, 2, 34 ]
ex
y = Array.new
y[0] = 543
How do you remove items from an array?
you can use the delete method
ex (by the values)
array.delete(values)
ex (by index)
array.delete_at(index)
ex ( by if)
array.delete_if { |value| some_code }
What is the join method?
The join method is used to join the different values in an array
ex
array = [1, 2, 3]
array.join(‘+’)
=> “1+2+3”
What is the push method?
The push method is when you add an element to an array at the end of the array
ex
array = [1, 2, 3]
array.push(4)
=> [1, 2, 3, 4]
What is the pop method?
The pop method is used to delete the last element in an array.
ex
array = [1, 2, 3, 4]
array.pop
=> [1, 2, 3]
How do you add an element to an array=
You add them
by push or by index
ex
array[index] = value
What is a hash?
A hash is an key value collection (also called dictionary)
How do create an hash?
ex (modern syntax)
hash = {first: 1, second: 2}
ex (old syntax)
hash = {“first” => 1, “second” => 2}
ex (old, but with symbol)
hash = {:first => 1, :second => 2}
How do you return a value from an hash based on a key?
hash[:key]
How do you delete an element from an hash?
with the delete method
ex
hash.delete(:key)
How do you iterate over just the keys in a hash?
You use the each_key method
ex
hash.each_key do |key|
some_code
end
How do you iterate over just the values in a hash?
You use the each_value method
ex
hash.each_value do |value|
some_code
end
How do you add to a hash?
hash[:key] = value
How do you reverse the keys and the values in a hash?
you use the invert method
ex
hash = {:first => 1, :second => 2}
hash.invert
=> {1 => :first, 2 => :second}
How do you merge two hashes?
with the merge method
ex
hash.merge(another_hash)
How do you convert a hash to an array
hash.to_a
How do write an if statement?
ex if condition some_code elsif condition some_code else some_code end
ex (simple)
some_code if conditional
What is an unless statement?
An unless statement runs code unless some condition becomes true
ex
unless conditional
some_code
end
ex
some_code unless conditional
How do you chain multiple conditionals together(compund conditional)?
With the && or || methods
ex (and symbol both must be true)
if conditional && conditional
some_code
end
ex (or symbol one must be true)
if conditional || conditional
some_code
end
How do you set up a class in ruby?
ex class ClassName
end
everything within the class will belong to the class
What is an initializer method?
It is a method that will run some code every time you create a new instance of the class. The initialize method will need some arguments that you need to pass in when you are creating a new instance of the class.
ex
def initialize(argument1, argument2)
some_code
end
Why is inheritance important?
In order not to repeat code it is easier to give inheritance to other classes. than rewrite the code for every class.
You have a parent class and the other classes (children) inherit from it.
How many responsibilities should a class have?
only one
What is a public method?
It means that the method is visible to others.
What is private method?
It means that only that specific class has access to that specific methods.
A secret method should only be called from within the class.
What is polymorphism?
It is when you override a method from a parent class with a method from a child class. You use polymorphism to give custom behaviour.
What is the super keyword?
It is when you want the same method both in the parent and child class to be called, instead of the child class method overriding the parent class method (polymorphism)
You write the super keyword in the child class whitin the method when you want it to be called.
How do you create a file?
ex
File.open(“file-path”, ‘options’) { |x| x.write(“something to write”)}
ex (alternate way)
variable = File.new(“file-path”, ‘options’)
variable.puts(“Some content”)
variable.close
options : r - reading a - appending to a file w - just writing w+ reading and writing a+ open a file for reading and appending r+ - opening a file for updating both reading and writing
How do you read from a file?
ex
variable = File.read(“file path”)
you can now treat the content of the file as you want.
How do you delete a file?
ex
File.delete(“file path”)
How do you update a file in ruby?
ex ( will add stuff to the file)
File.open(“file path” “a”) {|f| some_code}
What is the basic syntax for error handling in ruby?
not using Rspec
ex begin some code rescue some code end
How should you write errors in ruby? (not using Rspec)
ex begin some code rescue StandarError => variable puts "error message #{variable}" end
What is a regular expression?
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern.
what is the basic syntax for regular expressions?
=~ /matcher/
What is grep?
Grep is a method that is used to search through collections and objects.
ex
array.grep(search_object)
What are ruby gems?
Ruby gems are basically ruby code packaged.
What is metaprogramming in ruby?
It is the process of writing code that writes itself during runtime.
What is the w%( ) method?
it allows you to create an array from a string without adding commas and such.
What is the freeze method?
The freeze method makes an object unable to change.
How do you interact with an API with ruby?
You need a gem (httparty) to interact and you also need a class with methods.
What is a URI?
Uniform Resource Identifiers is a string of characters used to identify a resource.
The most common form of URI is the Uniform Resource Locator (URL),
Do you need to use a web framework like Rails or Sinatra to work with APIs?
No
What is a popular gem for working with APIs?
httparty
What type of data is typically sent back as an API response?
JSON
What is the sort method?
The sort method allows you to sort the elements inside an array.
What is the super keyword?
super calls the method of the parent class, if it exists. it passes all the arguments to the parent class method as well.
What are modules?
Modules are a way of grouping together methods, classes, and constants.
Modules give you two major benefits.
- Modules provide a namespace and prevent name clashes.
- Modules implement the mixin facility.
What is a mixin
Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
A mixin can basically be thought of as a set of code
that can be added to one or more classes to
add additional capabilities without using inheritance.
What is the & prefix?
the & prefix allows us to pass in a code block as a parameter like { print ‘Ho!’ }
What is Ruby?
Ruby is a high-level programming language
- Ruby is Interpreted (no need for a compiler)
- Object-oriented (allows users to manipulate data structures)
- Easy to use
What kind of data types are there in Ruby?
Integer = Number Numeric = class of number like float, fixnum Float = decimal number NilClass = The class of the singleton object nil. Hash = A Hash is a dictionary-like collection of unique keys and their values. Symbol = Symbol objects represent names and some strings inside the Ruby interpreter. Array = A list of objects Range = A Range represents an interval—a set of values with a beginning and an end.
What is a variable?
One of the most basic concepts in computer programming is the variable. You can think of a variable as a word or name that grasps a single value.
my_num = 25
What arithmetic operator are there in ruby?
addition +
subtraction -
multiplication *
division /
modulo %
exponentiation **
What is the difference between puts and print?
print just prints whatever you give it to the screen
puts (“put string”) prints out what you give it with an empty line
So the difference is that puts has one more line
added.
What is a method in ruby?
They are built in abilities that objects have.
For example methods can show you the length of a string or reverse the string.
What is an interpreter?
An interpreter is a program that takes your code and runs it, it shows the result in your console
How do you use a method?
Methods are used with a .
my_string = ‘i love pizza’ –> my_string.length –> 12
How do write a comment in ruby?
you use #
Everything behind the (on the same line) # will be commented out
How do you do a multiline comment in Ruby?
You use =begin and =end
Everything in between will be commented out, you can use this to explain complicated concepts.
What is a naming convention?
A naming convention is how the community writes code, local variables should be written in lowercase letters and words.
How do you declare or set a variable?
You use the =
my_number = 12
How can you call multiple methods on a variable?
by chaining
name.method1.method2.method3
What is chaining?
Chaining is that you call multiple methods on a variable
What is control flow?
Control flow is that we can select different outcomes depending on the environment and the input.
What is an if statement?
Ruby takes an if statement and decides if its true and runs code accordingly.
What is an else statement?
The else statement is the continuation of the if statement. This code runs after the if statement is false.
What is an elsif statement?
An elsif statement gives the if else statement more options.
What is an unless statement?
An if statement checks if something is true, An unless statement checks if something is false and runs code accordingly.
What is a comparator?
A comparator checks if two values are equal or not
we use == to check if they are equal and != if we want to check if two values are not equal.
What are the comparator for less or equal than?
less than <
less than or equal to <=
greater than >
Greater than or equal to >=
What are boolean operators?
Boolean operators are either true or false
- && (and)
- | | (or)
- ! (not)
What is an and operator?
- && (and), The expression is true if both statements before and after && are true
true && true => true
true && false => false
false && true => false
false && false => false
What is an Or-operator?
- | | (or) is an operator when at least one of the expressions are true
true || true # => true
true || false # => true
false || true # => true
false || false # => false
What is an Not-operator?
A not operator (!) makes any statement after the expression false
!true= false
What is gets.chomp?
Gets chomp is for getting user input from the terminal
What is the .downcase method?
the .downcase method takes the user input and converts it do lower case letters.
What is the .include? method
The include? method checks if the user input contains what we want
What is the .gsub! method?
The .gsub method stands for global substitution and changes all the chosen inputs.
string_to_change.gsub!(/s/, “th”)