fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,109 @@
---
title: Classes and Objects
---
## Classes and Objects
### Objects in Ruby
Let us quickly go over Ruby objects. In the real world, objects may be anything including a car, computer, or even a human. Each one of these objects has a state and behaviors.
Considering a car, then its state could be described as its model, make, and color. The behavior of the car could be turning, honking, or braking.
An object in Ruby has very similar characteristics. Ruby Objects also have a state and behavior. In Ruby Objects, the state is stored in instance variables and the behavior is stored in functions.
### Classes in Ruby
A class is basically a program template. This template defines the initial `properties` using `instance variables`. Again, there are also again `behaviors` defined in the form of functions.
A new instance of a class is created using the `initialize` method of a class.
Take for example the following sample code of a class:
```Ruby
class Car
def initialize(make, model, color)
@make = make
@model = model
@color = color
end
def turn(direction)
end
def honk
puts "beep beep"
end
def brake
end
end
```
As you saw, classes are defined using the `class` keyword and the class code block ends with an `end` keywork. The `.initialize` function is the constructor. When we create this object, we define the attributes `@make`, `@model`, and `@color` with values we pass into the constructor.
### Creating an Instance of a Class
Now, to create an instance of this class you only need to call the `.new` function.
```Ruby
mazda3 = Car.new('Mazda', 'Mazda3', 'White')
```
This is great, but sometimes you may need to change some of these attributes! Most of these attributes in this example would be static. Still, imagine that you decided to get a new paintjob. How would you go about updating the state of this instance of the `Car` object?
### Modifying Instance State
Thankfully, it is rather simple to update the state of an object. First, we would need a `setter` method! Ruby defines **getter** and **setter** settings as the `attr_reader` and `attr_accessor` respectively. For both getter and setter settings on a given attribute, you can also just use `attr_accessor`.
To demonstrate this, I have modified the previous Car object with these newly defined settings.
```Ruby
class Car
attr_accessor :color
attr_reader :make, :model
def initialize(make, model, color)
@make = make
@model = model
@color = color
end
def turn(direction)
end
def honk
puts "beep beep"
end
def brake
end
end
```
So now we can change state and read the state of the object.
```Ruby
irb(main):023:0> c = Car.new('Mazda', 'Mazda3', 'White')
=> #<Car:0x00007fd3ca13fdd0 @make="Mazda", @model="Mazda3", @color="White", @speed=nil>
irb(main):024:0> c.color
=> "White"
irb(main):025:0> c.make
=> "Mazda"
irb(main):026:0> c.model
=> "Mazda3"
irb(main):027:0> c.color = 'Brutal Blue'
=> "Brutal Blue"
irb(main):028:0> c.make = 'Prius'
Traceback (most recent call last):
2: from /usr/local/bin/irb:11:in `<main>'
1: from (irb):28
NoMethodError (undefined method `make=' for #<Car:0x00007fd3ca13fdd0>)
Did you mean? make
```
Viewing the previous output from `irb`, you can see that each one of the instance variables is readable. We can write to `@color`, but we end up causing a `NoMethodError` exception when we attempt to write to `@make`. This is because `@make` was only defined using an `attr_reader`, so `make=` is not defined.
### Resources
- [Ruby Programming/Syntax/Classes](https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes)

View File

@ -0,0 +1,219 @@
---
title: Common Array Methods
---
## Common Array Methods
Ruby Arrays form a core foundation in programming in Ruby, and most languages in fact. It is used so much that it would be beneficial to know and even memorize some of the most commonly used methods for arrays. If you want to know more about Ruby Arrays, we have [an article about them](https://guide.freecodecamp.org/ruby/ruby-arrays).
For the purpose of this guide, our array will be as follows:
``` ruby
array = [0, 1, 2, 3, 4]
```
#### .length
The .length method tallies the number of elements in your array and returns the count:
``` ruby
array.length
=> 5
```
This is also similar to .count and .size methods.
``` ruby
array.count
=> 5
```
``` ruby
array.size
=> 5
```
#### .first
The .first method accesses the first element of the array, the element at index 0:
``` ruby
array.first
=> 0
```
#### .last
The .last method accesses the last element of the array:
``` ruby
array.last
=> 4
```
#### .take
The .take method returns the first n elements of the array:
``` ruby
array.take(3)
=> [0, 1, 2]
```
#### .drop
The .drop method returns the elements after n elements of the array:
``` ruby
array.drop(3)
=> [3, 4]
```
#### array index
You can access a specific element in an array by accessing its index. If the index does not exist in the array, nil will be returned:
```ruby
array[2]
=> 2
array[5]
=> nil
```
#### .pop
The .pop method will permantently remove the last element of an array:
``` ruby
array.pop
=> [0, 1, 2, 3]
```
#### .shift
The .shift method will permantently remove the first element of an array and return this element:
``` ruby
array.shift
=> 0
array
=> [1, 2, 3, 4]
```
#### .push
The .push method will allow you to add an element to the end of an array:
``` ruby
array.push(99)
=> [0, 1, 2, 3, 4, 99]
```
#### .unshift
The .unshift method will allow you to add an element to the beginning of an array:
```
array = [2, 3]
array.unshift(1)
=> [1, 2, 3]
```
#### .delete
The .delete method removes a specified element from an array permanently:
``` ruby
array.delete(1)
=> [0, 2, 3, 4]
```
#### .delete_at
The .delete_at method allows you to permanently remove an element of an array at a specified index:
``` ruby
array.delete_at(0)
=> [1, 2, 3, 4]
```
#### .reverse
The .reverse method reverses the array but does not mutate it (the original array stays as is):
``` ruby
array.reverse
=> [4, 3, 2, 1, 0]
```
#### .select
The .select method iterates over an array and returns a new array that includes any items that return true to the expression provided.
``` ruby
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.select { |number| number > 4 }
=> [5, 6, 7, 8, 9, 10]
array
=> [5, 6, 7, 8, 9, 10]
```
#### .include?
The include? method checks to see if the argument given is included in the array:
``` ruby
array = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
array.include?(3)
=> true
#### .flatten
The flatten method can be used to take an array that contains nested arrays and create a one-dimensional array:
``` ruby
array = [1, 2, [3, 4, 5], [6, 7]]
array.flatten
=> [1, 2, 3, 4, 5, 6, 7]
```
#### .join
The .join method returns a string of all the elements of the array separated by a separator parameter. If the separator parameter is nil, the method uses an empty string as a separator between strings.
``` ruby
array.join
=> "1234"
array.join("*")
=> "1*2*3*4"
```
#### .each
The .each method iterates over each element of the array, allowing you to perform actions on them.
``` ruby
array.each do |element|
puts element
end
=>
0
1
2
3
4
```
#### .map
The .map method is the same as the .collect method. The .map and .collect methods iterate over each element of the array, allowing you to perform actions on them. The .map and .collect methods differ from the .each method in that they return an array containing the transformed elements.
``` ruby
array.map { |element| element * 2 }
puts element
end
=>
0
2
4
6
8
```
#### .uniq
The .uniq method takes in an array containing duplicate elements, and returns a copy of the array containing only unique elements--any duplicate elements are removed from the array.
``` ruby
array = [1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 6, 7, 8]
array.uniq
=> [1, 2, 3, 4, 5, 6, 7, 8]
```
#### .concat
The .concat method appends the elements from an array to the original array. The .concat method can take in multiple arrays as an argument, which will in turn append multiple arrays to the original array.
``` ruby
array = [0, 1, 2, 3, 4]
array.concat([5, 6, 7], [8, 9, 10])
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
## More Information
* [Ruby Array docs](http://ruby-doc.org/core-2.5.1/Array.html)

122
guide/english/ruby/index.md Normal file
View File

@ -0,0 +1,122 @@
---
title: Ruby
---
## What is Ruby?
Ruby was created by Yukihiro "Matz" Matsumoto and is an <a href='https://github.com/ruby/ruby' target='_blank' rel='nofollow'>open source</a>, dynamic and interpreted scripting language for quick and easy object-oriented programming. Which means:
It's also known to have one of the <a href="https://www.ruby-lang.org/en/community/">largest and friendly community</a> among programming languages.
* Ability to make operating system calls directly
* Immediate feedback during development
* Variable declarations are unnecessary
* Memory management is automatic
* Everything is an object
* Has "mixin" functionality by module
* Iterators and closures
If you are unfamiliar with some of the concepts above, read on, and don't worry. Ruby focus on simplicity and productivity with an elegant syntax that is natural to read and easy to write, like:
```ruby
# Quick example of Ruby with Object Oriented Programming
class Greeter
def initialize(name)
@name = name.capitalize
end
def salute
puts "Hello #{@name}!"
end
end
# Create a new object
g = Greeter.new("world")
# Output "Hello World!"
g.salute
```
## Version
The current stable version is [2.5.1](https://www.ruby-lang.org/en/news/2018/03/28/ruby-2-5-1-released/).
## Installation
Mac OS X and many Linux distributions come pre-installed with Ruby. To check if ruby is pre-installed in your system, just run `ruby -v` on your shell. There are several ways to install Ruby:
* When you are on a UNIX-like operating system, using your systems package manager is the easiest way of getting started. However, the packaged Ruby version usually is not the newest one.
* Installers can be used to install a specific or multiple Ruby versions. There is also an installer for Windows.
* Managers help you to switch between multiple Ruby installations on your system.
* And finally, you can also build Ruby from source.
To know about how to install Ruby through package managers, installers and source, click <a href='https://www.ruby-lang.org/en/documentation/installation/' target='_blank' rel='nofollow'>here</a>. RVM (Ruby Version Manager) and rbenv are the most popular Ruby managers to manage multiple Rubies. If you get stuck anywhere, don't worry, just head over to our <a href='https://gitter.im/FreeCodeCamp/ruby' target='_blank' rel='nofollow'>Gitter chat room</a> and ask us anything.
## IRB
IRB stands for Interactive Ruby Shell. The abbreviation irb comes from the fact that the filename extension for Ruby is ".rb", although interactive Ruby files do not have an extension of ".irb". The program is launched from a command line and allows the execution of Ruby commands with an immediate response, experimenting in real-time. It features command history, line editing capabilities, and job control, and is able to communicate directly as a shell script over the Internet and interact with a live server. It was developed by Keiju Ishitsuka.
```shell
irb
2.3.0 :001 > print "Hello World"
Hello World! => nil
```
## Ruby Interpreter
The Ruby interpreter is what is used to run Ruby scripts. If it is available and in Unix shells search path makes it possible to start it by typing the command `ruby` followed by the script name will invoke the interpreter and run the script.
`hello_campers.rb`
```ruby
if 'welcome' == 'welcome'
print('Hello campers!')
end
```
From command-line:
```shell
$ ruby hello_campers.rb
Hello campers!
```
## Documentation
Ruby is well <a href='https://www.ruby-lang.org/en/documentation/' target='_blank' rel='nofollow'>documented</a>. These docs include tutorials, guides, references and meta information for language.
Another important resouce for documentation is <a href='http://ruby-doc.org/core-2.3.0/' target='_blank' rel='nofollow'>Ruby Doc</a>. You should visit this <a href='https://github.com/airbnb/ruby' target='_blank' rel='nofollow'>link</a> to know more about Ruby style guide, written by developers of AirBnB.
A recommended read for beginners in Ruby is <a href='https://poignant.guide/' target='_blank' rel='nofollow'>Why's (Poignant) Guide to Ruby</a>
This book is unusual among programming books. With quite a lot of strange humor and narrative side tracks which are sometimes completely unrelated to the topic, this one manages to keep the readers entertained while they learn Ruby basics.
## Debugging
Inline `print` statements can be used for simple debugging:
```ruby
print some_variable # prints to console
```
> **... often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.**
Ruby also includes more powerful tools for debugging, such as:
* <a href='https://github.com/nixme/pry-debugger' target='_blank' rel='nofollow'>_pry-debugger_</a>
## Hello World!
Going back to the docs, we can read about the <a href='http://ruby-doc.org/core-2.3.0/Kernel.html#method-i-print' target='_blank' rel='nofollow'>`print`</a> method, one of the built-in methods of the <a href='http://ruby-doc.org/core-2.3.0/Kernel.html' target='_blank' rel='nofollow'>the Kernel module</a>.
```ruby
print(obj, ...) nil
```
Prints each object to $stdout. Objects that arent strings will be converted by calling their `to_s` method. The return value of print is `nil`. So when you run `print "Hello World!` in your IRB. The output is:
```shell
2.3.0 :001 > print "Hello World!"
Hello World!
=> nil
```
## Frameworks(gems)
Ruby has several frameworks(gems) for quickly scaffolding applications. The most popular by far is <a href='http://rubyonrails.org/' target='_blank' rel='nofollow'>Rails</a> which was initially released in 2004\. Other frameworks(gems) for Ruby include <a href='http://www.sinatrarb.com/' target='_blank' rel='nofollow'>Sinatra</a>, <a href='http://lotusrb.org/' target='_blank' rel='nofollow'>Lotus</a>, and <a href='http://voltframework.com/' target='_blank' rel='nofollow'>Volt</a>. Each of these options has their pros and cons for development and cater to a variety needs.
## Ruby Framework for mobile development
To write cross-platform native apps in Ruby, RUBY MOTION is used to develop cross-platform native apps for iOS, Android and OS X using the Ruby programming langauge.
More resources here: http://www.rubymotion.com/
## What after learning Ruby?
Every programming language plays an imporatnt role . You can contribute to a lot of open source projects or you can apply for some big companies after having a good grasp on Ruby. As many big internet sites such as Basecamp, Airbnb, Bleacher Report, Fab.com, Scribd, Groupon, Gumroad, Hulu, Kickstarter, Pitchfork, Sendgrid, Soundcloud, Square, Yammer, Crunchbase, Slideshare, Funny or Die, Zendesk, Github, Shopify are build on Ruby so, there are plenty of option for you out there.
Moreover, a lot of startups are hiring people who have skill in RUby on Rails as not many programmers try to learn Ruby. So,you might have a clear cut to work in a start-up company.
So, Ruby is beginner friendly and is quite hard skill set to find you have a good number of openings to work as a developer.

View File

@ -0,0 +1,79 @@
---
title: Managing Ruby versions
---
## Ruby has changed over time
Ruby was been in constant development since the 1990s, and like many languages,
there have been syntax changes across versions, so it is important to be clear
about which Ruby version your code expects.
Probably the most visible change came with Ruby 1.9; previously, we wrote
hashes like this:
```ruby
{ :one => 1, :two => 2, :three => 3 }
```
This use of the 'hashrocket' operator (`=>`) was so common, that Ruby 1.9
provided a shorthand:
```
{ one: 1, two: 2, three: 3 }
```
This older code run on any version, but the newer syntax will only run on Ruby 1.9+.
## How does this cause problems?
For example, you might have decided to use a Gem which internally relies on
Ruby 1.9 features; this means that your project now also relies on Ruby 1.9
features.
If you don't specify which version of Ruby your project needs, it can be very
confusing when code works on one machine, but not another.
As with most languages, it's considered good practice to specify the version of
Ruby that your code expects. This makes it much easier to manage multiple
projects on your development machine, each expecting a different version of
Ruby.
## How do I specify my Ruby version?
There are a couple of tools which are popular for this, but both have agreed to
share a common file. Many Ruby (or Rails) projects will include a simple
`.ruby-version` file, which simply specifies a version number, _eg_:
```
2.4.2
```
Popular tools to help you manage your Ruby version are:
* [Ruby Version Manager (RVM)](https://rvm.io)
* [rbenv](https://github.com/rbenv/rbenv)
Let's look at RVM.
### Using RVM
RVM is typically installed ([link](https://rvm.io)) on a Linux, Unix or MacOS
machine, and is very convenient as it hooks into the `cd` (`c`hange `d`irectory)
command so when you move to a new project, your `.ruby-version` is read
automatically, and you're automatically switched to the correct version of Ruby
before you start working.
For example, you might have this sequence:
```shell
% cd ~/projects/older-project
% ruby --version
ruby 2.3.5p376 (2017-09-14 revision 59905) [x86_64-darwin16]
% cd ~/projects/newer-project
% ruby --version
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]
```
(These examples are from a MacOS machine)

View File

@ -0,0 +1,87 @@
---
title: Rubocop
---
[Rubocop](https://github.com/bbatsov/rubocop) is a static analyis tool for
[Ruby](https://www.ruby-lang.org/en/). What does this mean? It means Rubocop
will to 'read' your code (as opposed to running it, hence the 'static' part
of the name), and analyse it. The analysis rules Rubocop uses are from the
[Ruby community style guide](https://github.com/bbatsov/ruby-style-guide).
The style guide is a set of specific suggestions about how to write code which
is more readable, more expressive, and more conventional. As a community, it
would be terrific if we could read anyone else's code easily, and they could
read ours easily. This is what Rubocop helps us to do. This sort of tool is
always valuable, but it's particularly useful when you're learning Ruby, and
you may code which is _correct_, but which doesn't stick to Ruby conventions,
or doesn't take advantage of some of Ruby's more powerful features.
Most usefully, Rubocop can automatically fix many of the minor warnings - like
incorrect spacing. This is very helpful before code review as it means your
fellow developers can focus on higher level concerns, and not have to waste
time on syntax issues.
## Using Rubocop
### Installation
Rubocop is delivered as a Gem, so on a typical project which uses Bundler you
would add it to the development section of your `Gemfile`:
```
group :development do
gem rubocop
end
```
This means anyone using your project will have the same version of Rubocop, and
everyone will agree on what the current best practice is.
### Usage
Before every commit, I like to check that my newly modified code complies with
the commmunity standard, simply by running:
```
rubocop
```
This will output a list of warnings about your code.
It can be helpful to ask Rubocop for more help:
```
rubocop --extra-details --display-cop-names
```
(You might add these to a `.rubocop` file to make them default.)
Many editors will allow you to integrate Rubocop, which can give immediate
feedback when you're writing code.
### Fixing issues
Let's say I've written some new code; before I commit it, I might decide to
check it sticks to the guidelines:
```shell
rubocop <my new file>
```
I can edit make the suggested changes manually, or I can ask Rubocop to fix
minor issues automatically:
```
rubocop --auto-correct
```
### Running only certain Cops
Each community guideline is implemented in a Rubocop 'cop'. When working on a
legacy codebase you might be swamped with warnings when introducing Rubocop.
In this case it can often be useful to run only a single cop across the
codebase, and check those changes in before moving on to the next guideline, for
example:
```
rubocop --auto-correct --only 'Layout/EmptyLineAfterMagicComment'
```
### Text Editor Integration
Rubocop can be integrated with Vim, Visual Studio Code, Atom, and other text editors. A full list can be found [here](https://rubocop.readthedocs.io/en/latest/integration_with_other_tools/).

View File

@ -0,0 +1,47 @@
---
title: Ruby Arrays
---
## Ruby Arrays
An array represents a list of values. The individual values are often called "elements" of the array. To make an array in Ruby, use square brackets and separate values with commas:
```ruby
my_array = [1, 2, 3, 4, 5]
```
That first example is an array of numbers, but a Ruby array can contain values of different types, even other arrays:
```ruby
mixed_array = [5, "Hello World", true, [1,2,3]]
```
You can access the elements of an array with square brackets and numerical indexes. Notice that the first element is at index 0, not 1:
```ruby
mixed_array[0] # 5
mixed_array[1] # "Hello World"
mixed_array[2] # true
```
You can check how many elements an array has with the `length` method:
```ruby
mixed_array.length # 3
[].length # 0
```
You can check the first element of an array with the `first` method:
```ruby
mixed_array.first # 5
```
You can check the last element of an array with the `last` method:
```ruby
mixed_array.last # true
```
#### More Information:
<a href='https://ruby-doc.org/core-2.4.2/Array.html' target='_blank' rel='nofollow'>Ruby array documentation</a>

View File

@ -0,0 +1,47 @@
---
title: Ruby Comments
---
<h1>Ruby Comments</h1>
Comments are lines of annotation within code that are ignored at runtime (meaning they are visible within the source code but aren't printed out when you run the program).
In Ruby, a single line comment starts with the `#` character and extends to the end of the line. The comment can be on its own line or following code.
```Ruby
puts "Learning to code is fun!"
# I am a single line comment.
puts "Ruby is a great language!" # Me too - I am a trailing comment.
```
When executed, the program above produces the following:
```
Learning to code is fun!
Ruby is a great language!
```
You can do multiple line comments by putting the comments between `=begin` and `=end`. `=begin` and `=end` must start at the very beginning of the line and `=end` must be on a line of its own.
```ruby
=begin
I am a multi-line comment
and I can be as long as I please.
See, still going!
=end
puts "Hello World!"
=begin It's ok to start the comment on the same
line as "=begin" (though it's more readable if
you don't) but you can't put a space or any
text before "=begin" or "=end" and you can't put
anything on the same line after "=end".
=end
```
When executed, the program above produces the following:
```
Hello World!
```

View File

@ -0,0 +1,55 @@
---
title: Ruby Conditionals
---
Ruby has several commonly used conditionals.
## If Statements
An extremely common conditional in many programming languages, the statement tests if the condition is true, then branches into the specified action. An if statement consists of one `if`,
any number of `elsif` and at most one `else` statement.
* ```ruby
fruit = :apple
if fruit == :apple
puts "Your fruit is an apple"
elsif fruit == :orange
puts "Your fruit is an orange"
else
puts "This is not an apple or an orange"
end
```
### Unless statement
An unless statement is the opposite of an if statement. It is the same as a negated if statement.
* ```ruby
happy = true
if !happy
puts "This person is not happy"
end
```
The above statement equal to the statement below
* ```ruby
unless happy
puts "This person is not happy"
end
```
## Ternary Statement
A ternary statement is used as a short conditional statement. It is written as follows
* ```ruby
game = "won"
fans = game == "won" ? "happy" : unhappy
fans # => "happy"
```
## Case Statement
A case statement is similar to an if/elsif/else statement
* ```ruby
fruit = :apple
case fruit
when :apple
puts "Your fruit is an apple"
when :orange
puts "Your fruit is an orange"
else
puts "This is not an apple or an orange"
end
```

View File

@ -0,0 +1,31 @@
---
title: Ruby For Loops
---
## Ruby For Loops
Ruby for loops are used to loop or iterate over a number of elements and execute of block of code for each element. For loops are often used on arrays. See section on <a href='https://github.com/freeCodeCamp/guides/blob/master/src/pages/ruby/ruby-arrays/index.md' target='_blank' rel='nofollow'>Ruby Arrays</a>.
For loops are merely one example of looping or iterating over elements. Below is an example of a for loop:
```
for element in array do
puts element
end
```
There are many many different ways in which you can execute a for loop or loop in Ruby, another such example would be:
```
element.each do |element|
puts element
end
```
This would achieve exactly the same results as the aforementioned for loop, it is however neater and more efficient as it makes use of Array's built in methods.
To go one step further, we can write the above loop in the following way:
```
element.each do { |element| puts element }
```

View File

@ -0,0 +1,43 @@
---
title: Ruby Hash
---
## Ruby Hash
A hash represents a collection of distinct key, value pairs. It is also called associative arrays. To create a hash in Ruby , use curly brackets and separate each key-value pair with comma.
```ruby
my_hash = {:key1 => "value", :key2 => "value2"}
```
You can create a hash in the following ways
```ruby
my_hash = Hash.new # with empty hash
my_hash = {:key1 => "value", :key2 => "value2"} # with key's and value's defined
```
You can access the value of key in a hash with square brackets and key references
```ruby
my_hash[:key1] # value
my_hash[:key2] # value2
```
You can assign a new key and value for an already defined hash
```ruby
my_hash[:key3] = "value3" # {:key1=>"value", :key2=>"value2", :key3=>"value3"}
```
You can check how many elements a hash has with the `length` method:
```ruby
my_hash.length # 2
```
You can also create integers as hash key but the syntax is different from the usual one
```ruby
my_hash = {1: "value"} # will raise an exception
my_hash = {1 => "value"} # will create hash with corresponding key value pair
```

View File

@ -0,0 +1,44 @@
---
title: Ruby Hashes
---
## Ruby Hashes
A hash is a collection of keys and values. It is similar to what is commonly called a dictionary in other languages. In Ruby, a hash is similar to an <a href='https://raw.githubusercontent.com/freeCodeCamp/guides/master/src/pages/ruby/ruby-arrays/index.md' target='_blank' rel='nofollow'>array</a>, but rather than simply storing a value it stores a key, value pair.
```ruby
array = ["value"]
hash = { "key" => "value" }
```
There are a couple of different ways to create a new hash:
```ruby
hash1 = {a: 100, b: "200"}
hash2 = Hash.new
hash3 = Hash.new(0) # with default value set to 0
```
A programmer can then access a hash value using its key, rather than the index.
```ruby
array[0] # => "value"
hash["key"] # => "value"
```
In this way, a hash acts more like a dictionary where you can look up a value by its key.
```ruby
dictionary = { "Aardvark" => "a large, nocturnal, burrowing mammal",
"Zyzzyva" => "a genus of tropical weevils" }
dictionary["Aardvark"] # => "a large, nocturnal, burrowing mammal"
dictionary["Zyzzyva"] # => "a genus of tropical weevils"
```
You can also create a hash using [symbols](#) as keys.
```ruby
hash = { :symbol => "value" }
hash[:symbol] # => "value"
```
In addition, if all of your keys are [symbols](#), you can write your hash in this alternate format, but you would access it in the same manner:
```ruby
hash = { symbol: "value" }
hash[:symbol] # => "value"
```
#### More Information:
<a href='https://ruby-doc.org/core-2.4.2/Hash.html' target='_blank' rel='nofollow'>Ruby hash documentation</a>

View File

@ -0,0 +1,39 @@
---
title: Ruby Methods
---
## Introduction
Have you ever heard of programming languages referring to functions? If you've coded in the likes of JavaScript you should be all too familiar with them. Ruby also has functions but we refer to them as Methods. Methods are just bundled blocks of code that are given a name for ease of use and accessibility and are crucial to that DRY (do not repeat yourself) approach in programming.
## Creating and using methods
Methods should always be defined as lowercase (you can separate the words with an underscore if you like) else they may be confused as constants. Methods should also be defined before actually trying to call them, so the rule of thumb would be creating your methods at the beginning of your file and calling them afterward where needed. Always try and avoid single word method names where necessary, you want to be able to know more or less what the method does without having to dig inside.
## Syntax
Methods are quite easy to create, they can be created without the ability to accept parameters, with parameters and even with pre-defined parameters if none is given.
#### Simple method
```
def my_method
code goes here
end
```
#### Parameter accepting method
```
def my_method (param1, param2)
param1 + param2
end
```
#### Predefined paramter method (predefined parameters are used when none are given)
```
def my_method (param1 = parameter1, param2 = parameter2)
parm1 + parm2
end
```
## Return in Methods
The returned value of a method will always be the last evaluated expression in the method. You can, however, use the return keyword to return more than one value if required.

View File

@ -0,0 +1,88 @@
---
title: Ruby Number Methods
---
Ruby provides a variety of built-in methods you may use on numbers. The following is an incomplete list of <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>integer</a> and <a href='https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil' target='_blank' rel='nofollow'>float</a> methods.
## <a href='https://ruby-doc.org/core-2.2.0/Integer.html#method-i-even-3F' target='_blank' rel='nofollow'>Even</a>:
Use `.even?` to check whether or not an <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a> is even. Returns a `true` or `false` **boolean**.
```Ruby
15.even? #=> false
4.even? #=> true
```
## <a href='https://ruby-doc.org/core-2.2.0/Integer.html#method-i-odd-3F' target='_blank' rel='nofollow'>Odd</a>:
Use `.odd?` to check whether or not an <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a> is odd. Returns a `true` or `false` **boolean**.
```Ruby
15.odd? #=> true
4.odd? #=> false
```
## <a href='https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil' target='_blank' rel='nofollow'>Ceil</a>:
The `.ceil` method rounds <a href='https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil' target='_blank' rel='nofollow'>**floats**</a> **up** to the nearest number. Returns an <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a>.
```Ruby
8.3.ceil #=> 9
6.7.ceil #=> 7
```
## <a href='https://ruby-doc.org/core-2.2.0/Float.html#method-i-floor' target='_blank' rel='nofollow'>Floor</a>:
The `.floor` method rounds <a href='https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil' target='_blank' rel='nofollow'>**floats**</a> **down** to the nearest number. Returns an <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a>.
```Ruby
8.3.floor #=> 8
6.7.floor #=> 6
```
## <a href='https://ruby-doc.org/core-2.2.0/Integer.html#method-i-next' target='_blank' rel='nofollow'>Next</a>:
Use `.next` to return the next consecutive <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a>.
```Ruby
15.next #=> 16
2.next #=> 3
-4.next #=> -3
```
## <a href='https://ruby-doc.org/core-1.8.7/Integer.html#method-i-pred' target='_blank' rel='nofollow'>Pred</a>:
Use `.pred` to return the previous consecutive <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a>.
```Ruby
15.pred #=> 14
2.pred #=> 1
(-4).pred #=> -5
```
## <a href='https://ruby-doc.org/core-2.4.2/Object.html#method-i-to_s' target='_blank' rel='nofollow'>To String</a>:
Using `.to_s` on a number (<a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a>, <a href='https://ruby-doc.org/core-2.2.0/Float.html#method-i-ceil' target='_blank' rel='nofollow'>**floats**</a>, etc.) returns a <a href='https://ruby-doc.org/core-2.2.0/String.html' target='_blank' rel='nofollow'>string</a> of that number.
```Ruby
15.to_s #=> "15"
3.4.to_s #=> "3.4"
```
## <a href='https://ruby-doc.org/core-2.2.0/Integer.html#method-i-gcd' target='_blank' rel='nofollow'>Greatest Common Denominator</a>:
The `.gcd` method provides the greatest common divisor (always positive) of two numbers. Returns an <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a>.
```Ruby
15.gcd(5) #=> 5
3.gcd(-7) #=> 1
```
## <a href='http://ruby-doc.org/core-2.2.0/Integer.html#method-i-round' target='_blank' rel='nofollow'>Round</a>:
Use `.round` to return a rounded <a href='https://ruby-doc.org/core-2.2.0/Integer.html' target='_blank' rel='nofollow'>**integer**</a> or <a href='https://ruby-doc.org/core-2.2.0/Float.html' target='_blank' rel='nofollow'>**float**</a>.
```Ruby
1.round #=> 1
1.round(2) #=> 1.0
15.round(-1) #=> 20
```
## <a href='http://ruby-doc.org/core-2.2.0/Integer.html#method-i-times' target='_blank' rel='nofollow'>Times</a>:
Use `.times` to iterate the given block ```int``` times.
```Ruby
5.times do |i|
print i, " "
end
#=> 0 1 2 3 4
```

View File

@ -0,0 +1,46 @@
---
title: Ruby Numbers Operations
---
In Ruby you can perform all standard math operations on numbers, including: addition `+`, subtraction `-`, multiplication `*`, division `/`, find remainders `%`, and work with exponents `**`.
## Addition:
* Numbers can be added together using the `+` operator.
```ruby
15 + 25 #=> 40
```
## Subtraction:
* Numbers can be subtracted from one another using the `-` operator.
```ruby
25 - 15 #=> 10
```
## Multiplication:
* Numbers can be multiplied together using the `*` operator.
```ruby
10 * 5 #=> 50
```
## Division:
* Numbers can be divided by one another using the `/` operator.
```ruby
10 / 5 #=> 2
```
## Remainders:
* Remainders can be found using the modulus `%` operator.
```ruby
10 % 3 #=> 1 # because the remainder of 10/3 is 1
```
## Exponents:
* Exponents can be calculated using the `**` operator.
```ruby
2 ** 3 #=> 8 # because 2 to the third power, or 2 * 2 * 2 = 8
```

View File

@ -0,0 +1,105 @@
---
title: Ruby on Rails
---
# Ruby on Rails
[Ruby on Rails](http://rubyonrails.org/) is a server-side framework (gem) built on the Ruby language to make websites. Rails makes web development faster, easier and more fun. It includes everything you need to build fantastic applications and has a big community. Rails was created by David Heinemeir Hansson and is currently on it's 5th version. Rails emphasizes the use of other well-known software engineering patterns and paradigms, including [convention over configuration (CoC)](https://en.wikipedia.org/wiki/Convention_over_configuration), [don't repeat yourself (DRY)](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), and the active record pattern. Rails is a [modelviewcontroller (MVC)](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) framework, providing default structures for a database, a web service, and web pages. Lately, Rails has integrated an API module to make the creation of web-services faster and easier.
## Installing Rails
Rails is downloaded in the same way as any other Ruby gem: with the `gem install` command. Before we download it, we'll need to <a href='https://www.ruby-lang.org' target='_blank' rel='nofollow'>download Ruby</a>. Afterwards we're only 3 words away from starting with Ruby on Rails:
```shell
$ gem install rails
```
## Setting Up database
Rails ships with sqlite3 as the default database, which is a simple file on disk. You need to install MySQL or PostgreSQL if you want to use something more robust.
## Creating a Rails application
1. After you install Ruby on Rails, it's very simple to create a brand new application, we'll just need 3 more words:
```shell
$ rails new your_application_name
```
* If you want to use MySQL
```shell
$ rails new <application_name> -d mysql
```
* If you want to use Postgres
```shell
$ rails new <application_name> -d postgresql
```
2. This command will create a folder with the *your_application_name* you informed in the last command. Next step is to go to the new directory you've just created:
```shell
$ cd your_application_name
```
3. Get the necessary gems and software packages before running your application:
```shell
$ bundle install
```
4. To run the rails server and see if everything went accordingly is also fast:
```shell
$ rails server
```
It couldn't be anymore simple! Well, this isn't actually 100% true, we could make it even smaller by reducing the `rails server` command to:
```shell
$ rails s
```
5. Now, with your preferred browser, go to `http://localhost:3000` and you'll see: "Yay! Youre on Rails!"
### Alternative method for creating a Rails application
1. Create a new directory:
```shell
$ mkdir <application_name>
```
2. Go into the new directory:
```shell
$ cd <application_name>
```
3. Create the Rails application using the Unix dot notation. This results in assigning the name of the directory to the new application.
```shell
$ rails new .
```
5. Start exploring the framework of the application you just created. The folder structure is organized according to the table below:
| File/Folder | Purpose |
| ----------- | ------- |
| app/ | Contains the controllers, models, views, helpers, mailers, channels, jobs and assets for your application. You'll focus on this folder for the remainder of this guide. |
| bin/ | Contains the rails script that starts your app and can contain other scripts you use to setup, update, deploy or run your application. |
| config/ | Configure your application's routes, database, and more. This is covered in more detail in Configuring Rails Applications. |
| config.ru | Rack configuration for Rack based servers used to start the application. |
| db/ | Contains your current database schema, as well as the database migrations. |
| Gemfile, Gemfile.lock | These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the Bundler website. |
| lib/ | Extended modules for your application. |
| log/ | Application log files. |
| public/ | The only folder seen by the world as-is. Contains static files and compiled assets. |
| Rakefile | This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application. |
| README.md | This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on. |
| test/ | Unit tests, fixtures, and other test apparatus. These are covered in Testing Rails Applications. |
| tmp/ | Temporary files (like cache and pid files). |
| vendor/ | A place for all third-party code. In a typical Rails application this includes vendored gems. |
| .gitignore | This file tells git which files (or patterns) it should ignore. See Github - Ignoring files for more info about ignoring files. |
A great place to getting started with this awesome framework is reading his [Getting Started page](http://guides.rubyonrails.org/getting_started.html).
## Convention over Configuration
*Convention over Configuration* means a developer only needs to specify unconventional aspects of the application. For example, if there is a class `Sale` in the model, the corresponding table in the database is called `sales` by default. It is only if one deviates from this convention, such as calling the table "products sold", that the developer needs to write code regarding these names. Generally, Ruby on Rails conventions lead to less code and less repetition.
## What is MVC?
Model (Active record) contains the business logic and interacts with the database.
Views (Action views) all of the HTML files and structure.
Controller (Action controller) interacts with the views and model to direct the actions of the application.
## DRY - Don't Repeat Yourself
*Don't repeat yourself* means that information is located in a single, unambiguous place. For example, using the ActiveRecord module of Rails, the developer does not need to specify database column names in class definitions. Instead, Ruby on Rails can retrieve this information from the database based on the class name.
## Ruby on Rails is open source
Not only is it free to use, you can also help make it better. More than 4,500 people have already contributed code to [Rails](https://github.com/rails/rails). Its easier than you think to become one of them.

View File

@ -0,0 +1,30 @@
---
title: Ruby String Interpolation
---
# String Interpolation
String interpolation provides a more readable and concise syntax for building strings. You may be familiar with concatenation via the `+` or `<<` methods:
```ruby
"Hello " + "World!" #=> Hello World
"Hello " << "World!" #=> Hello World
```
String interpolation provides a way to embed Ruby code directly into a string:
```ruby
place = "World"
"Hello #{place}!" #=> Hello World!
"4 + 4 is #{4 + 4}" #=> 4 + 4 is 8
```
Everything between `#{` and `}` is evaluated as Ruby code. In order to do so, the string must be surrounded by double quotes (`"`).
Single quotes will return the exact string inside the quotes:
```ruby
place = "World"
'Hello #{place}!' #=> Hello #{place}!
```

View File

@ -0,0 +1,193 @@
---
title: Ruby String Methods
---
## Ruby String Methods
Ruby has many built in methods to work with strings. Strings in Ruby by default are mutable and can be changed in place or a new string can be returned from a method.
### Length:
* The `.length` property returns the number of characters in a string including white-space.
```ruby
"Hello".length #=> 5
"Hello World!".length #=> 12
```
### Empty:
* The `.empty?` method returns `true` if a string has a length of zero.
```ruby
"Hello".empty? #=> false
"!".empty? #=> false
" ".empty? #=> false
"".empty? #=> true
```
### Count:
* The `.count` method counts how many times a specific character(s) is found in a string.
* This method is case-sensitive.
```ruby
"HELLO".count('L') #=> 2
"HELLO WORLD!".count('LO') #=> 1
```
### Insert:
* The `.insert` method inserts a string into another string before a given index.
```ruby
"Hello".insert(3, "hi5") #=> Helhi5lo # "hi5" is inserted into the string right before the second 'l' which is at index 3
```
### Upcase:
* The `.upcase` method transforms all letters in a string to uppercase.
```ruby
"Hello".upcase #=> HELLO
```
### Downcase:
* The `.downcase` method transforms all letters in a string to lowercase.
```ruby
"Hello".downcase #=> hello
```
### Swapcase
* The `.swapcase` method transforms the uppercase latters in a string to lowercase and the lowercase letters to uppercase.
```ruby
"hELLO wORLD".swapcase #=> Hello World
```
### Capitalize:
* The `.capitalize` method make the first letter in a string uppercase and the rest of the string lowercase.
```ruby
"HELLO".capitalize #=> Hello
"HELLO, HOW ARE YOU?".capitalize #=> Hello, how are you?
```
_Note that the first letter is only capitalized if it is at the beginning of the string._
```ruby
"-HELLO".capitalize #=> -hello
"1HELLO".capitalize #=> 1hello
```
### Reverse:
* The `.reverse` method reverses the order of the characters in a string.
```ruby
"Hello World!".reverse #=> "!dlroW olleH"
```
### Split:
* The `.split` takes a strings and _splits_ it into an array, then returns the array.
```ruby
"Hello, how are you?".split #=> ["Hello,", "how", "are", "you?"]
```
* The default method splits the string based on whitespace, unless a different separator is provided (see second example).
```ruby
"H-e-l-l-o".split('-') #=> ["H", "e", "l", "l", "o"]
```
* To split a word in to individual letters :
``` ruby
"hello".split("") #=> ["h", "e", "l", "l", "o"]
```
### Chop:
* The `.chop` method removes the last character of the string.
* A new string is returned, unless you use the `.chop!` method which mutates the original string.
```ruby
"Name".chop #=> Nam
```
```ruby
name = "Batman"
name.chop
name == "Batma" #=> false
```
```ruby
name = "Batman"
name.chop!
name == "Batma" #=> true
```
### Strip:
* The `.strip` method removes the leading and trailing whitespace on strings, including tabs, newlines, and carriage returns (`\t`, `\n`, `\r`).
```ruby
" Hello ".strip #=> Hello
```
### Chomp:
* The `.chomp` method removes the last character in a string, only if its a carriage return or newline (`\r`, `\n`).
* This method is commonly used with the `gets` command to remove returns from user input.
```ruby
"hello\r".chomp #=> hello
"hello\t".chomp #=> hello\t # because tabs and other whitespace remain intact when using `chomp`
```
### To Integer:
* The `.to_i` method converts a string to an integer.
```ruby
"15".to_i #=> 15 # integer
```
### Gsub:
* `gsub` replaces every reference of the first parameter for the second parameter on a string.
```ruby
"ruby is cool".gsub("cool", "very cool") #=> "ruby is very cool"
```
* `gsub` also accepts patterns (like *regexp*) as first parameter, allowing things like:
```ruby
"ruby is cool".gsub(/[aeiou]/, "*") #=> "r*by *s c**l"
```
### Concatenation:
* Ruby implements some methods to concatenate two strings together:
* The `+` method:
```ruby
"15" + "15" #=> "1515" # string
```
* The `<<` method:
```ruby
"15" << "15" #=> "1515" # string
```
* The `concat` method:
```ruby
"15".concat "15" #=> "1515" # string
```
### Index:
* The `index` method returns the index position of the first occurrance of the substring or regular expression pattern match in a string.
* If there is no match found, `nil` is returned.
* A second optional parameter indicates which index position in the string to begin searching for a match.
```ruby
"information".index('o') #=> 3
"information".index('mat') #=> 5
"information".index(/[abc]/) #=> 6
"information".index('o', 5) #=> 9
"information".index('z') #=> nil
```
### Clear:
* Removes string content.
```ruby
a = "abcde"
a.clear #=> ""
```

View File

@ -0,0 +1,47 @@
---
title: Ruby String Operations
---
Both concatenation and multiplication can be performed on strings.
## Concatenation:
* Strings can be joined together using any of the following methods:
* `+` operator
* `<<` operator
* `.concat` method
```ruby
"Hello" + " World" + "!" #=> Hello World!
```
```ruby
"Hello" << " World!" #=> Hello World!
```
```ruby
string1 = "Hello"
string2 = " World!"
string1.concat(string2) #=> Hello World!
```
## Multiplication:
* Strings can be multiplied by an integer value using the `*` operator.
```ruby
"Hello" * 3 #=> HelloHelloHello
```
## Replacing a substring
*   We can search for sub-strings or use Regex for searching and replacing character within a string.
```ruby
"Hey mom, look at this string".sub('mom', 'dad') #=> Hey dad, look at this string
```
## Comparison:
* Strings can be compared, returns -1, 0, +1 or nil depending on whether string is less than, equal to, or greater than other_string.
```ruby
"abcdef" <=> "abcde" #=> 1
"abcdef" <=> "abcdef" #=> 0
"abcdef" <=> "abcdefg" #=> -1
"abcdef" <=> "ABCDEF"   #=> 1
```

View File

@ -0,0 +1,118 @@
---
title: Ruby Symbols
---
## Ruby Symbols
A symbol looks like a variable name but it's prefixed with a colon. Examples - :action, :line_items. You don't have to pre-declare a symbol and they are guaranteed to be unique. There's no need to assign some kind of value to a symbol - Ruby takes care of that for you. Ruby also guarantees that no matter where it appears in your program, a particular symbol will have the same value.
Alternatively, you can consider the colon to mean "thing named" so :id is "the thing named id." You can also think of :id as meaning the name of the variable id, and plain id as meaning the value of the variable.
For ex: Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.
```ruby
module One
class Fred
end
$f1 = :Fred
end
module Two
Fred = 1
$f2 = :Fred
end
def Fred()
end
$f3 = :Fred
$f1.object_id #=> 2514190
$f2.object_id #=> 2514190
$f3.object_id #=> 2514190
```
## Working with Symbols
You can recognise a Ruby Symbol because it will be a word that starts with a :.
So far weve seen them as the key in a Hash (Working with Hashes in Ruby):
```ruby
person = {:name => "Philip"}
```
So the first thing we can do is to inspect a Symbol to see what class it uses:
```ruby
:hello.class
=> Symbol
"hello".class
=> String
```
So we can see that Symbols and Strings are instances of two different objects.
You can call String-like methods such as `upcase`, `downcase` and `capitalize` on Symbols:
```ruby
:hello.upcase
=> :HELLO
:HELLO.downcase
=> :hello
:hello.capitalize
=> :Hello
```
## Why would you use a Symbol instead of a String?
So if a Symbol is just an immutable String, why would you use it, and why is there a special distinction in Ruby?
## Symbols are Immutable
Firstly, one of the big reasons is, as I mentioned above, Symbols are immutable. Unforeseen bugs can crop up in your application when a value can change. If you need to ensure that the value of an object should never change, its much safer to use an immutable object.
However, with that being said, it is possible to make a String immutable in Ruby by calling the `freeze` method:
```ruby
name = "Philip"
=> "Philip"
name.freeze
=> "Philip"
name << "Jim"
RuntimeError: cant modify frozen String
```
As you can see in the example above, once you call the freeze method on a String instance, you can no longer modify it.
So why else would you use Symbols instead of Strings?
#### Symbols are better for performance
A second reason why you would use a Symbol over a String in certain situations is because Symbols are much better for performance.
For example:
```ruby
philip".object_id
=> 70288511587360
"philip".object_id
=> 70288504327720
:philip.object_id
=> 539368
:philip.object_id
=> 539368
```
When you create two String objects with the same value, those two objects are treated as two different objects. When you create a Symbol, referencing the Symbol will always use the same object.
This is much better for performance because the same String object will be created and destroyed over and over again when in reality the same object can just be reused each time.
#### Public Class Methods
all_symbols => array click to toggle source
Returns an array of all the symbols currently in Ruby's symbol table.
```ruby
Symbol.all_symbols.size #=> 903
Symbol.all_symbols[1,20] #=> [:floor, :ARGV, :Binding, :symlink,
:chown, :EOFError, :$;, :String,
:LOCK_SH, :"setuid?", :$<,
:default_proc, :compact, :extend,
:Tms, :getwd, :$=, :ThreadGroup,
:wait2, :$>]
```
#### More Information:
<a href='http://ruby-doc.org/core-2.5.1/Symbol.html' target='_blank' rel='nofollow'>Ruby Symbols Documentation</a>

View File

@ -0,0 +1,60 @@
---
title: True, False, and Nil
---
<h1>True, False, and Nil</h1>
`true`, `false`, and `nil` are special built-in data types in Ruby. Each of these keywords evaluates to an object that is the sole instance of its respective class.
```ruby
true.class
=> TrueClass
false.class
=> FalseClass
nil.class
=> NilClass
```
`true` and `false` are Ruby's native boolean values. A boolean value is a value that can only be one of two possible values: true or not true. The object `true` represents truth, while `false` represents the opposite. You can assign variables to `true` / `false`, pass them to methods, and generally use them as you would other objects (such as numbers, Strings, Arrays, Hashes).
`nil` is a special value that indicates the absence of a value: it is Ruby's way of referring to "nothing". An example of when you will encounter the `nil` object is when you ask for something that doesn't exist or cannot be found:
```ruby
hats = ["beret", "sombrero", "beanie", "fez", "flatcap"]
hats[0]
=> "beret" # the hat at index 0
hats[2]
=> "beanie" # the hat at index 2
hats[4]
=> "flatcap" # the hat at index 4
hats[5]
=> nil # there is no hat at index 5, index 5 holds nothing (nil)
```
Zero is not nothing (it's a number, which is something). Likewise, empty strings, arrays, and hashes are not nothing (they are objects, which happen to be empty). You can call the method `nil?` to check whether an object is nil.
```ruby
0.nil?
=> false
"".nil?
=> false
[].nil?
=> false
{}.nil?
=> false
nil.nil?
=> true
# from the example above
hats[5].nil?
=> true
```
Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are "truthy" and those considered false are "falsey." In Ruby, <em>only</em> `false` and `nil` are "falsey," everything else is "truthy."
<h3>Other Resources</h3>
* https://ruby-doc.org/core-2.3.0/TrueClass.html
* https://ruby-doc.org/core-2.3.0/FalseClass.html
* https://ruby-doc.org/core-2.3.0/NilClass.html
* https://en.wikipedia.org/wiki/Boolean