Ruby is a dynamic, interpreted, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro Matsumoto "Matz" in Japan. "Wikipedia"
Here I am trying to keep track of my progress in Ruby and share whatever I am learning with sample projects and some explanations.
Note: To reach my goal I selected Ruby course in codecademy. The following info is extracted form this course. I will enrich my knowledge in this field sooner when my course resume in GA after holiday.
🎬 (22/12/2018)
lesson1: (23/12/2018)
- Parentheses and semicolon are not important in Ruby. ((Unlike Js))
- By convention - in regular old local variables - variables should start with a lowercase letter and words should be separated by underscores. ((In comparison with camelCase in Js))
- Exponentiation
**− Performs exponential (power) calculation on operators. (e.g.2 ** 3 == 8) - Using
putsandprintto print the result in terminal. (Instead ofconsole.log()in Js.) - The difference between
putsandprintis the result will be printed in separated lines inputswhile they coming successively in one line inprint. - To write a comment that spans multiple lines it starts with
=beginand ends with=end. Everything between these two expressions will be a comment. ((In Js we have/*to start and*/to end our multiple lines comment.)) - Ruby has string interpolation for those cases you want to print a string including a string variable. You should use
#{variable's name}to refer that variable inside of outer string. ((In Js we use${}!)) - Using
!at the end of a method which coming along with a variable modifies the value contained within that variable in-place. We don't need to assign the result to another variable.
Methods
upcasecapitalizegets.chomp:getsis the Ruby method that gets input from the user. When getting input, Ruby automatically adds a blank line (or newline) after each bit of input;chompremoves that extra line.
lesson2:
ifstatements will finish withend.- We have
unlessstatements in Ruby for when you want to use control flow to check if something is false, rather than if it's true! - As a general rule, Ruby methods that end with
?evaluate to the boolean values true or false.
Methods
downcaseincludegsub: stands for global substitution.
lesson3: (24/12/2018)
while,untilandforloops end withendsame asifstatements.- The complement to the
whileloop is theuntilloop. It's similar towhileloop. But said it is sort of like a backwardwhile! - In this piece of code
for number in 1...10if we have three dots means exclude 10 but if we have two dots means include the final number (10). - There's more than one way to accomplish a given task in Ruby. Between iterators the simplest one is the
loopmethod. - In Ruby, curly braces
{}are generally interchangeable with the keywordsdo(to open the block) andend(to close it). - The
breakkeyword breaks a loop as soon as its condition is met. - The
nextkeyword can be used to skip over certain steps in the loop. - Inside of
| |can be anything you like: it's just a placeholder for each element of the object you're usingeachmethod on.
Methods
eachtimes: is like a super compactforloop. (e.g.2.times { puts "I am learning Ruby!" })split: takes in a string and returns an array.
lesson4:
- Arrays of arrays are called multidimensional arrays. For example
multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]is a two-dimensional array. - Hashes are sort of like JavaScript objects or Python dictionaries. Hash is a collection of key-value pairs.
- In Hash values are assigned to keys using
=>. ((In Js we use colon:)) - To print values and keys we can use
eachmethod:hash_name.each { |x, y| puts "#{x}: #{y}" }.
Methods
Hash.new: creates an empty hash.Hashmust be capitalized!sort_by: sorts elements from smallest to largest by value count. This method returns an array of arrays. (The syntax is likehash.sort_by { |x, y| y })reverseto_s: converts the value to a string.
lesson5: (27/12/2018)
defdefines method in Ruby. ((function in Js))- Methods end with
endkeyword. - Splat arguments are arguments preceded by a
*, which tells the program that the method can receive one or more arguments. - Blocks can be defined with either the keywords
doandendor with curly braces{}. - The combined comparison operator:
<=>. It returns0if the first operand (item to be compared) equals the second,1if the first operand is greater than the second, and-1if the first operand is less than the second.
Methods
sort: sorting items alphabetically or in ascending order.
lesson6: (28/12/2018)
falseandnilare two non-true values in Ruby. It's important to realize thatfalseandnilare not the same thing:falsemeans "not true", whilenilis Ruby's way of saying "nothing at all."- If you try to access a key in a hash that doesn't exist the result will be
nil. - When you give a default value to your hash so if you try to access a nonexistent key in that hash you will get that default as a result not
nil! - Symbols always start with a colon
:. They must be valid Ruby variable names, so the first character after the colon has to be a letter or underscore_; after that, any combination of letters, numbers, and underscores is allowed. - You can use either string or symbol as Ruby hash keys. A Ruby symbol is a sort of name. It's important to remember that symbols aren't strings.
"string" == :string # false - One of the differences between string and symbol is while there can be multiple different strings that all have the same value, there's only one copy of any particular symbol at a given time.
- In Ruby 1.9 the hash syntax changed. The two changes are: You put the colon at the end of the symbol, not at the beginning; and You don't need the hash rocket anymore.
casestatement is likeif/elsestatement. It is suitable when we have a lot of conditions and comes withwhenfor each condition.- General info to add, display, update and delete data we have an acronym which is called CRUD for Create, Read, Update and Delete.
Methods
object_id: gets the ID of an object. It's how Ruby knows whether two objects are the exact same object.to_sym: converts to symbol.to_i: converts a string to an integer.intern: internalizes the string into a symbol and works just liketo_sym.select: filters for values that meet certain criteria.each_key: iterates over just keys.each_value: iterates over just values.delete:hash.delete(key)
lesson7: (29/12/2018)
- In Ruby you can write your code in different ways; you have different alternatives. In
ifandunlessstatements:
if condition unless condition
# Do something! or # Do something!
end end
if the "do something" is a short, simple expression, we can move it up into a single line like:
expression if boolean or expression unless boolean
in this case the order is important and you don't need an end when you write your if or unless statement all on one line.
- ternary conditional expression:
boolean ? Do this #if true: Do this #if false
puts 2 < 3 ? "2 is less than 3!" : "2 is not less than 2."
- In
casestatement you can compress your code like:
case ---
when "---" then puts "----"
when "---" then puts "----"
else puts "----"
end
||=: conditional assignment operator. We can assign a value to a variable if it hasn't already been assigned! If we assigned a value before, it still prints out the value of the previous position.- implicit return: If we do not ask Ruby to
returnthe result in ourdefRuby automatically will return the result of the last evaluated expression! No problem!☺️ <<: concatenation operator (also known as "the shovel") to add an element to the end of an array or a string.
Methods
upto: counts up to certain number or letter.downto: counts down to certain number or letter.respond_to?: takes a symbol and returnstrueif an object can receive that method andfalseotherwise. For example:
[1, 2, 3].respond_to?(:push) #true
it is true because we can call push method on an array.
lesson8: (30/12/2018)
-
yield- When a method expects a block, it invokes it by calling the yield function. Actuallyyieldallows you to "inject" that block of code at some place into a method. -
Proc: a "saved" block. It is just like you can give a bit of code a name and turn it into a method, you can name a block and turn it into aProc.Procs are great for keeping your code DRY. With blocks, you have to write your code out each time you need it; with aProc, you write your code once and can use it many times!
multiples_of_3 = Proc.new do |n| # we should call Proc.new to save a block of code.
n % 3 == 0
end
&: is used to convert the namedProcinto a block when we are going to use it.
cube = Proc.new { |x| x ** 3 }
[4, 5, 6].map!(&cube)
- By using
&you can also convert symbols toprocs!
array = ["5", "10", "15"]
integer = array.map(&:to_i)
# ==> [5, 10, 15]
lambda: is likeprocan object. They are identical toprocs.
lambda { puts "-----" } in comparison with Proc.new { puts "-----" }
- Differences between
lambdaandproc:- First, a
lambdachecks the number of arguments passed to it, while aprocdoes not. This means that alambdawill throw an error if you pass it the wrong number of arguments, whereas aprocwill ignore unexpected arguments and assign nil to any that are missing. - Second, when a
lambdareturns, it passes control back to the calling method; when aprocreturns, it does so immediately, without going back to the calling method.
- First, a
Methods
collect: takes a block and applies the expression in the block to every element in an array. ((likemapin Js))map=collect- We have both in Ruby! 😌floor: rounds a number with a decimal down to the nearest integer. ((likeMath.floorin Js))call: callsprocdirectly.
execute = Proc.new { # do execute my code }
execute.call
is_a?: returnstrueif an object is the type of object named andfalseotherwise. Note: You should always type object named afteris_a?with a capital letter!
:string.is_a? Symbol
# the answer is true
lesson9:
class: is just a way of organizing and producing objects with similar attributes and methods. By convention,classnames start with a capital letter and use CamelCase instead of relying_on_underscores.- In Ruby, we use
@before a variable to signify that it's an Instance variable. This means that the variable is attached to the instance of the class. - Global variables can be declared in two ways.
- Define the variables outside of any method or class.
- Start it with
$if you want to make a variable global from inside a method or class.
- Class variables starts with
@@. Class variables are attached to entire classes. - 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 read
<as "inherits from" in the following code:
class ChildClass < ParentClass
# Some code!
end
superkeyword - when you callsuperfrom inside a method, that tells Ruby to look in the superClass/parentClass of the current class and find a method with the same name and use it.- Note: Any given Ruby class can have only one superClass/parentClass.
- Fancy trick to save more time and space: If you want to end a Ruby statement without going to a new line, you can just type a semicolon.
class SubClass < SupperClass; end
lesson10: (03/01/2018)
publicmethod: allows for an interface with the rest of the program. This part of your program can be reached by everyone.privatemethod: is for your classes to do its own work undisturbed. This part of your program will be unreachable!- In order to access
privateinformation, we have to createpublicmethods that know how to get it. This separates the private implementation from the public interface. attr_readerto access an instance variable inside aclassinstead of adding another method to do so. We just need to pass our instance variables (as symbols) toattr_reader.
attr_reader :name
attr_writerto change an instance variable inside aclass.
attr_writer :name
attr_accessor: if we want to both read and write a particular instance variable in aclass.
