diff --git a/coding_conventions.md b/coding_conventions.md
index 485379d..bac9ad0 100644
--- a/coding_conventions.md
+++ b/coding_conventions.md
@@ -20,20 +20,20 @@ The examples below make it more clear:
This:
-```
+```ruby
task :rake => pre_rake_task do
something
end
```
Really means:
-```
+```ruby
task(:rake => pre_rake_task){ something }
```
And this with curly braces:
-```
+```ruby
task :rake => pre_rake_task {
something
}
@@ -41,7 +41,7 @@ task :rake => pre_rake_task {
really means:
-```
+```ruby
task :rake => (pre_rake_task { something })
```
@@ -61,7 +61,7 @@ Unlike JS where many developers use ```CamelCase``` for their variable naming co
####Functions that return booleans
For functions that return a boolean value, the name should be suffixed with a ```?```. For example:
-```
+```ruby
str.include? "substring"
```
@@ -70,7 +70,7 @@ In other languages like Java or C#, if we have an attribute ```name```, and we h
Ruby allows ```=``` in method names so the convention is to suffix the ```=``` with the attribute. So in this case, it would be:
-```
+```ruby
def name=(value)
@name = value
end
@@ -90,15 +90,15 @@ Most of the time, if this is a common instance variable, you do not need to set
###String Concatenation vs String Formatting and Interpolation
-```
+```ruby
#bad
email_with_name = user.name + ' <' + user.email + '> '
```
-```
+```ruby
#good (with string interpolation)
email_with_name = "#{user.name} <#{user.email}>"
```
-```
+```ruby
#good (with string formatting)
email_with_name = format('%s <%s>', user.name, user.email)
```
@@ -116,7 +116,7 @@ According to the [unofficial Ruby style guide](https://github.com/bbatsov/ruby-s
From the aforementioned style guide:
-```
+```ruby
class Person
attr_reader :name, :age
diff --git a/functions.md b/functions.md
index 513a0e2..adcc1c5 100644
--- a/functions.md
+++ b/functions.md
@@ -11,7 +11,7 @@ Many functions such as sort, each and times allow you to specify a code block to
For example, in Ruby, if you wanted to print "Hello" 5 times, you could do:
-```
+```ruby
# The code inside the curly braces is a block that is passed to the function 'times'
5.times { puts "Hello" }
```
@@ -21,7 +21,7 @@ If you want to pass in a code block as a valid parameter to a function, you need
**IMPORTANT:** Like the [splat arguments](#splat-arguments), this needs to be defined as a parameter of the function **last**
-```
+```ruby
#Note the '&' before the 'func' argument in the method definition
def foo(&func)
func.call
@@ -43,7 +43,7 @@ To reference a proc inside a function, you use the ```&``` prefix with the name
See below:
-```
+```ruby
times_2 = Proc.new { |num| num * 2 } #define the proc
[1,2,3].map(×_2) #note how the proc is prefixed with the '&'
# => [2,4,6]
@@ -53,14 +53,14 @@ times_2 = Proc.new { |num| num * 2 } #define the proc
To call procs directly, use the ```call``` method like so:
-```
+```ruby
hello = Proc.new { puts 'Hello World' }
hello.call # => Hello World
```
**WARNING:** using ```return``` inside a proc will cause it to not only exit out of the proc but return outside of the calling function. See below:
-```
+```ruby
def foo
some_proc.call #The return in this proc will kick us out of function foo
return 'Goodbye' #This never gets executed :'(
@@ -73,7 +73,7 @@ foo
So:
-```
+```ruby
'Goodbye' #Expected
'Hello' #Actual :(
```
@@ -84,7 +84,7 @@ In Ruby, there is a bit of shorthand notations which will, for most JS developer
Converting symbols to Procs is one such example. See this example below:
-```
+```ruby
["1", "2", "3"].map(&:to_i) # => [1,2,3]
```
@@ -99,7 +99,7 @@ What is happening is:
So....:
-```
+```ruby
["1", "2", "3"].map(&:to_i) # => [1,2,3]
["1", "2", "3"].map { |arg| arg.to_i } # same as the above statement
```
@@ -109,7 +109,7 @@ So....:
###What are lamdas?
A lambda is a ```proc``` but with a few small additions. It is declared almost the same way as a proc.
-```
+```ruby
foo = Proc.new { puts "Hello World" }
bar = lamda { puts "Goodbye Cruel World" }
```
@@ -121,7 +121,7 @@ Nope. Lambdas and procs have 2 major differences:
1. Lambdas check the number of arguments passed to it while procs do not. This means if a lambda has 3 arguments and is passed 2, it throws an error. Procs on the other hand just assign ```nil``` to any missing arguments.
2. Unlike procs, when a return statement is hit inside a lambda, it only exits out of the lambda and not out of the calling method.
-```
+```ruby
foo = lambda { |x, y| x + y }
def bar
@@ -132,7 +132,7 @@ end
bar
```
-```
+```ruby
foo = lambda { |x,y| return x + y } #The return only exits out of lambda, not calling method
def bar
@@ -147,7 +147,7 @@ bar # Returns 'Hello' not 11
To pass procs/lambdas as parameters to functions for actions such as filtering, use the ```&``` to refer to the proc/lambda. This essentially unpackages/unwraps the code block from the proc/lambda
-```
+```ruby
stuff = [:hello, :goodbye, 'Hello', 'Goodbye']
is_symbol = Proc.new { |val| val.is_a? Symbol } #Lets filter out anything that isn't a symbol
@@ -163,7 +163,7 @@ To define a function, the ```def``` keyword is used and is wrapped with an ```en
For example:
-```
+```ruby
#Function that takes in no args
def foo
puts 'Hello World'
@@ -172,7 +172,7 @@ end
or:
-```
+```ruby
#function that takes in 1 argument
def foo(name)
puts "Hello #{name}!"
@@ -183,7 +183,7 @@ end
If you want to return something, you can use the ```return``` keyword. **HOWEVER, if the last line of a function is the return statement, then the ```return``` keyword isn't needed. Ruby will automatically return the last variable set or retrieved without the return keyword. See below:
-```
+```ruby
#bad
def foo
name = 'hello'
@@ -198,7 +198,7 @@ end
Another example:
-```
+```ruby
def times_2(n):
n * 2 #Ruby will auto return this value without the return statement.
end
@@ -207,7 +207,7 @@ end
A ```return``` IS needed if this is **NOT** the last line of the function
-```
+```ruby
def foo(x):
return "hello" if x == "friend"
return "hater!" if x == "hater"
@@ -219,7 +219,7 @@ end
####Functions with an arbitrary number of arguments using splat (```*```)
In Java, you would define an arbitrary number of arguments of the same type via the ```...``` keyword like so:
-```
+```ruby
#in Java
public void function(int ... numbers) { ... }
```
@@ -228,7 +228,7 @@ In Ruby, the splat arguments keyword ```*``` is used. This tells ruby that *we d
For example:
-```
+```ruby
def todd_five(greeting, *bros)
bros.each { |bro| puts "#{greeting}, #{bro}!" }
end
@@ -241,14 +241,14 @@ todd_five("Innuendo Five!", "J.D", "Turk")
In JavaScript, it is mandatory to execute function with no arguments with parentheses but in ruby, parentheses aren't required and so most devs don't use them:
-```
+```ruby
SomeClass.foo #This is equivalent to SomeClass.foo() in JS
```
###Executing functions with one or more known parameters
Unlike JS, in Ruby, parameters don't need to be enclosed by parentheses. The Ruby intepreter just looks for the parameters to be seperated by commas.
-```
+```ruby
puts 'Hello' 'World' 'Goodbye' # Similar to console.log('Hello', 'World', 'Goodbye')
puts('Hello', 'World') # Also correct in Ruby but less used as its unneccessary
```
@@ -263,7 +263,7 @@ See the [Coding Conventions](coding_conventions.md#parentheses) page for more de
In Ruby, functions can be passed blocks via {} which act similar to anonymous functions in JavaScript (see below)
-```
+```ruby
books = {}
books['stuff'] = 'hello' #setting a key and value is the same as in JS
books.values.each { puts 'Hello' } //equivalent to books.values.each(function(){ console.log('Hello') }); in JS
@@ -274,7 +274,7 @@ Some JS functions do their changes to an object in place and some don't. Ruby, h
Executing the function and ending with ! makes the change in-place. For example:
-```
+```ruby
name = "Gautham"
puts name.upcase # => "GAUTHAM"
puts name # => "Gautham" (the name wasn't changed)
@@ -284,7 +284,7 @@ puts name # => "GAUTHAM" (the name was changed when ! was specified in p
For functions with parameters, the ```!``` comes before the parameters
-```
+```ruby
str = "sea shells by the sea shore"
str.gsub!(/s/, "th") # Note how the ! is before the parameters
print str # Returns "thea thhellth by the thea thhore"
@@ -292,7 +292,7 @@ print str # Returns "thea thhellth by the thea thhore"
Note that you cannot use the '!' to try to do an inplace change if the original type and resulting type from the operation are different.
-```
+```ruby
str = 'Hello'
str.to_i! #This will return an error. String and integer are not the same type
str = str.to_i #The workaround
@@ -303,13 +303,13 @@ str = str.to_i #The workaround
In Ruby, parameters to anonymous functions are enclosed via | or "pipe" characters like so:
-```
+```ruby
books.values.each { |book| puts 'Gotta read ' + book }
```
which is equivalent to in JavaScript:
-```
+```ruby
books.values.each(function(book) {
console.log('Gotta read ' + book);
});
@@ -322,7 +322,7 @@ As a refresher, a block is just a reusable piece of code enclosed by braces ```{
Using the ```yield``` you can invoke code blocks and pass it arguments as if they were functions. **Unless the blocks are specified as arguments, they are outside the parentheses. See below:**
-```
+```ruby
def foo(greeting)
puts 'Inside the function foo'
yield(greeting)
@@ -333,7 +333,7 @@ foo("Top of the mornin to ya!") { |greeting| puts "#{greeting} John" }
This prints out:
-```
+```ruby
Inside the function foo
Top of the mornin to ya John
Back inside the function foo
diff --git a/looping_and_control_statements.md b/looping_and_control_statements.md
index da27cca..6ea8b37 100644
--- a/looping_and_control_statements.md
+++ b/looping_and_control_statements.md
@@ -4,13 +4,13 @@
In JS, we sometimes want to only set the value of a variable if its not already defined. To do that in JS, we would do something like this:
-```
+```ruby
some_var = some_var || {}
```
In Ruby, there is an even cooler and more terse way (Yey for terseness!). Here is how to write the aforementioned statement in Ruby:
-```
+```ruby
some_var ||= {} #This is similar to a += or /= operator
```
@@ -18,7 +18,7 @@ some_var ||= {} #This is similar to a += or /= operator
This works just like the JavaScript version but with one small enhancement: it can be used inline with other statements (in a very cool readable way). See below:
-```
+```ruby
puts "Hello Bruce" if name == 'Bruce'
```
@@ -26,7 +26,7 @@ puts "Hello Bruce" if name == 'Bruce'
This is similar to the if condition except it will execute the statement if the result is **false**
-```
+```ruby
i = 0
unless i == 3
print "Hooray it's not 3!" #will execute if the i == 3 is false which it is.
@@ -36,7 +36,7 @@ end
You could also use the unless statement inline with other statements (in an almost backwards if statement). See below:
-```
+```ruby
#Doing a type check to see if its an integer. The ? is just a naming convention to indicate it returns a boolean
puts "That's not an integer bro!" unless some_int.is_a? Integer
```
@@ -46,7 +46,7 @@ What is called Switch statements in JS and Java and other languages is called si
This in Ruby:
-```
+```ruby
case language
when "JS"
puts "Dat frontend scripting language!"
@@ -59,7 +59,7 @@ end
or a more terse way to write it using ```when...then```:
-```
+```ruby
case language
when "JS" then puts "Dat frontend scripting language!"
when "Java" then puts "Aw man. The kingdom of nouns!"
@@ -69,7 +69,7 @@ end
is equivalent to in JS:
-```
+```ruby
switch(language) {
case "JS":
puts "Dat frotnend scripting language";
@@ -98,7 +98,7 @@ There are two forms for this:
See example below:
-```
+```ruby
for i in 0..10 # same as "for(var i = 0; i <= 10; i++)" in JS. NOTE THE TWO DOTS FOR 10 inclusive
#some code
end
@@ -115,7 +115,7 @@ In Ruby, there is another way to loop through code called the ```loop``` stateme
For example:
-```
+```ruby
#Ruby way to do it
i = 0
loop do
@@ -127,7 +127,7 @@ end
This is equivalent to this do..while in JS:
-```
+```ruby
var i = 0;
do {
i += 1;
@@ -139,7 +139,7 @@ do {
Just like how the ```unless``` keyword is the opposite of the ```if``` statement, the ```while``` also has its opposite: ```until```. It is used in a similar way to ```unless```.
-```
+```ruby
#The following code loops until j = 0 and then breaks out of the loop.
j = 3
until j == 0 do
@@ -155,7 +155,7 @@ You can use the 'next' keyword to skip the loop if a condition is met. It is equ
For example:
-```
+```ruby
for i in 1..5
next if i % 2 == 0 #skip if its an even number
puts i
@@ -164,7 +164,7 @@ end
Equivalent to JS's continue used with an if statement:
-```
+```ruby
for (var i = 0; i <= 5; i++) {
if (i % 2 == 0) {
continue;
@@ -181,7 +181,7 @@ You specify an object to loop through and then specify a code block to run for e
For example, the following in Ruby:
-```
+```ruby
object = ['hello', 'goodbye']
object.each { |str| puts str }
@@ -192,7 +192,7 @@ end
```
is equivalent to in JS:
-```
+```javascript
var object = ['hello', 'goodbye'];
object.each(function(str) {
console.log(str);
@@ -201,7 +201,7 @@ object.each(function(str) {
To iterate over hashes (i.e JS objects), you can specify 1 parameter (where the parameter can be both the key and value) or 2 parameters (one for key and one for value):
-```
+```ruby
person = {
'name' => 'Goku',
'power_level' => 9000000000
@@ -227,7 +227,7 @@ The reason for this is due to the way the iterator is setup for the each.
If you want to make a block of code execute a fixed number of times, the best way to do it would be through a "times" loop
-```
+```ruby
3.times { puts "Hello!" } #Prints "Hello!" 3 times.
```
diff --git a/primitives_and_other_basics.md b/primitives_and_other_basics.md
index 47d1c03..80632a2 100644
--- a/primitives_and_other_basics.md
+++ b/primitives_and_other_basics.md
@@ -6,13 +6,13 @@
Single line comments in Ruby are defined via:
-```
+```ruby
# This is a comment
```
Multiline comments are enclosed via ```=begin``` and ```=end```
-```
+```ruby
=begin
Hello World
This is a multiline
@@ -24,13 +24,13 @@ comment
Semicolons are not necessary and not recommended to be used unless you have multiple statements of code onto one line.
-```
+```ruby
#bad use of semicolons!
puts 'hello world';
puts 'goodbye cruel world';
```
-```
+```ruby
#good use of semicolons
puts 'hello world'; puts 'goodbye cruel world';
```
@@ -42,7 +42,7 @@ In JavaScript, to print something to the console, you can use the ```Console```
The differences are **exactly the same as** Java's ```System.out.println``` and ```System.out.print``` respectively in that:
-```
+```ruby
puts 'Hello' # prints and adds a newline at the end (Similar to Java's System.out.println())
print 'Hello' # prints but no newline is added (Similar to Java's System.out.print())
@@ -66,7 +66,7 @@ puts 'Hello'
To reference variables already defined, use the ```#{variable_name}```. For example:
-```
+```ruby
name = 'Gautham'
puts 'Hello #{name}'
```
@@ -76,7 +76,7 @@ In Ruby, to read input from the user, its with the ```gets``` keyword (puts for
There is one caveat to the ```gets``` keyword and that it returns the User's input WITH a newline character.
-```
+```ruby
puts "Hello. What is your name?"
name = gets # If you entered 'Jake', then name='Jake\n'
```
@@ -84,7 +84,7 @@ name = gets # If you entered 'Jake', then name='Jake\n'
####Removing the newline character from ```gets```
To remove the newline character added from ```gets```, use the ```chomp``` function.
-```
+```ruby
name = gets.chomp # With chomp, it strips the '\n' and so name='Jake'
```
@@ -97,13 +97,13 @@ Objects in JavaScript are called hashes in Ruby.
In JS and Ruby, an empty hash can be defined like so:
-```
+```javascript
stuff = {}
```
JS and Ruby both can use ```:``` to seperate key value pairs in hashes like so:
-```
+```ruby
#the same in both JS and Ruby
a = { status: 'zombie', name:'Katie', id: 5 }
```
@@ -113,7 +113,7 @@ a = { status: 'zombie', name:'Katie', id: 5 }
Instead of using ```:``` to seperate key value pairs, In Ruby, one can also use ```=>``` instead.
-```
+```ruby
stuff = {
'name' => 'Bilbo Baggins',
'survives' => true
@@ -121,7 +121,7 @@ stuff = {
```
Equivalent JS:
-```
+```javascript
stuff = {
name: 'Bilbo Baggins',
survives: true
@@ -132,7 +132,7 @@ stuff = {
Hash.new takes in an optional parameter for the default value. If set, anytime a non-existent key is accessed or an operation is done on a key that has no value, this default value is returned instead.
-```
+```ruby
x = Hash.new #Creating a blank hash with the default value as nil
stuff = Hash.new(0) #Creating a new object and setting the default value to 0.
stuff[a] = 3; # => 3
@@ -148,14 +148,14 @@ Strings works pretty much the same way in JS as it does in Ruby with a few nice
###String Interpolation
Aside from standard string concatenation, Ruby allows something called String interpolation. This allows you to refer to variables from inside a string using the ```#{}``` syntax:
-```
+```ruby
name = 'Batman'
puts "#{name}" # => Batman
```
You can even execute functions from inside the ```#{}```
-```
+```ruby
puts "#{name.upcase}" # => BATMAN
```
@@ -164,7 +164,7 @@ String interpolation is not possible with single quotes. If single quotes are sp
**You MUST use double quotes for string interpolation to be done**
-```
+```ruby
name = 'Batman'
puts 'I am #{name}' # => 'I am #{name}'
puts "I am #{name}" # => 'I am Batman'
@@ -176,7 +176,7 @@ Arrays work the same as in JS with one or two small tweaks.
In Ruby, there is an alias for the push function using the ```<<``` operator. It can be used like so:
-```
+```ruby
[3,2] << 5 # => [3,2,5]
[3,2].push(5) # same as above statement and the JS-y way to do it but NOT conventional
```
@@ -205,7 +205,7 @@ This returns,
In this regard, you can think of the combined comparison operator as a glorified shorthand for the ```compareTo``` function in JS and Java
-```
+```ruby
'Hello' <=> 'Hello' # => 0
3 <=> 2 # => 1
3 <=> 9 # => -1
@@ -221,7 +221,7 @@ To check to make sure that the two objects point to the same point in memory, yo
###Checking Types
To check the type of an object, use ```is_a?``` function
-```
+```ruby
greeting = 'Hello'
greeting.is_a? Integer # Checking if greeting is an Integer. => false
greeting.is_a? String # Checking if greeting is a String. => true
@@ -232,14 +232,14 @@ greeting.is_a? String # Checking if greeting is a String. => true
####To a string
Converting to a String involves using the ```to_s``` function
-```
+```ruby
3.to_s # => "3"
```
####To an integer
Involves using the ```to_i``` function
-```
+```ruby
'Hello'.to_i # => 0
```
@@ -258,7 +258,7 @@ Symbols can only be values set to other objects.
They are defined via ":". Here are some examples:
-```
+```ruby
:hello
:'Hello World' # If you want to use symbol names with spaces
:"Hello World" # Ruby doesn't care whether you use single or double quotes like JS
@@ -280,7 +280,7 @@ Unlike JS, Ruby has no preincrement ```++i```, postincrement ```i++```, predecre
So instead, Ruby uses +=/-= operator
-```
+```ruby
i++ # throws an error in Ruby
i += 1 # Right way
```
diff --git a/ruby_oop_design.md b/ruby_oop_design.md
index 4258f18..5db9cd0 100644
--- a/ruby_oop_design.md
+++ b/ruby_oop_design.md
@@ -17,7 +17,7 @@ Finally, Class names are written in `CamelCase` not ```snake_case```
Here is a simplistic example:
-```
+```ruby
class Superhero
def initialize(pseudonym, name)
@pseudonym = pseudonym
@@ -39,7 +39,7 @@ Unlike JS which uses a nonstandard prototypal inheritence, Ruby has a more class
Here is a basic example:
-```
+```ruby
class Agent
def hijack_person
puts 'I got them. Intercepting them now.'
@@ -73,7 +73,7 @@ This is just like all other languages, just name the function the same as in the
If you have overriden a parent class function but now still need access to the parent class function, you can use the ```super``` keyword like you would in Java.
-```
+```ruby
class Dog
def speak
puts "I'm a dog."
@@ -95,7 +95,7 @@ Ruby allows a nice shortcut for this using the ```attr_reader```, ```attr_writer
Instead of writing your getter and setter function like so:
-```
+```ruby
class Foo
@name #just creating the instance var. currently 'nil'
@@ -114,7 +114,7 @@ a.name = 'Billy'
you can just write this:
-```
+```ruby
class Foo
attr_accessor :name #The name of the attribute written as a symbol.
end
@@ -147,7 +147,7 @@ Unlike JS which is all based on a function scope, this has 4 different scopes:
A good example of using class variables is for counting the instances of a class
-```
+```ruby
class Foo
@@foo_instance_count = 0
@@ -174,7 +174,7 @@ A module in Ruby is a data structure for holding methods and constants. It can b
Just like classes, they have a ```CamelCase``` naming convention.
-```
+```ruby
module Foo
SOME_CONSTANT = 9
end
@@ -186,7 +186,7 @@ If there are multiple functions with the same name in different modules, to make
For example. if you define a module with the constant PI
-```
+```ruby
module Foo
PI = 3.1415
end
@@ -194,13 +194,13 @@ end
Then if you want to refer to the Math module's PI and not Foo's, you can specify it like so:
-```
+```ruby
Math::PI #=> 3.141592653589793
```
You can also use the standard dot notation as well **IF it is a function**
-```
+```ruby
Date::Today
Date.Today #same as Date::Today
```
@@ -216,14 +216,14 @@ There are two ways to import a module:
Importing a module in Ruby uses the ```require``` keyword like so:
-```
+```ruby
require 'date' #import the date module. Note how the name is surrounded by quotes.
Date.today # date.today
```
Unlike with ```require```, importing a module with ```include``` means the module must **NOT** be wrapped as a string. It also must be imported from within a module or class.
-```
+```ruby
class Foo
include Math
def cosine(radians)
@@ -239,7 +239,7 @@ When you use ```include```, the module's methods act as if they are now part of
See below:
-```
+```ruby
module Gun
def shoot(name)
puts "Shot #{name}"
@@ -258,7 +258,7 @@ As you can see, the Man class was essentially augmented with the module's functi
Let's continue:
-```
+```ruby
class BadMan < Man; end
will = BadMan.new
@@ -272,7 +272,7 @@ The mixin with ```extend``` works exactly the same way as the [mixin with includ
See example below (thanks code academy for the example):
-```
+```ruby
module ThePresent
def now
puts "It's #{Time.new.hour > 12 ? Time.new.hour - 12 : Time.new.hour}:#{Time.new.min} #{Time.new.hour > 12 ? 'PM' : 'AM'} (GMT)."