Skip to content

Commit

Permalink
Merge branch 'master' of github.com:gauthamchandra/ruby-learning-notes
Browse files Browse the repository at this point in the history
  • Loading branch information
gauthamchandra committed Sep 2, 2015
2 parents 11ac0b3 + e0c73b9 commit 3f27a1f
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 99 deletions.
20 changes: 10 additions & 10 deletions coding_conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,28 @@ 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
}
```

really means:

```
```ruby
task :rake => (pre_rake_task { something })
```

Expand All @@ -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"
```

Expand All @@ -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
Expand All @@ -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)
```
Expand All @@ -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

Expand Down
66 changes: 35 additions & 31 deletions functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
```
Expand All @@ -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
Expand All @@ -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(&times_2) #note how the proc is prefixed with the '&'
# => [2,4,6]
Expand All @@ -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 :'(
Expand All @@ -73,7 +73,7 @@ foo

So:

```
```ruby
'Goodbye' #Expected
'Hello' #Actual :(
```
Expand All @@ -84,11 +84,15 @@ 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]
```

Most devs will probably be like [Lol Wuuuuut?](http://replygif.net/i/311.gif). Everything is fairly normal until we hit the ```&:to_i```
Most devs will probably be like...

![](http://replygif.net/i/311.gif)

Everything is fairly normal until we hit the ```&:to_i```


What is happening is:
Expand All @@ -99,7 +103,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
```
Expand All @@ -109,7 +113,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" }
```
Expand All @@ -121,7 +125,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
Expand All @@ -132,7 +136,7 @@ end
bar
```

```
```ruby
foo = lambda { |x,y| return x + y } #The return only exits out of lambda, not calling method

def bar
Expand All @@ -147,7 +151,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

Expand All @@ -163,7 +167,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'
Expand All @@ -172,7 +176,7 @@ end

or:

```
```ruby
#function that takes in 1 argument
def foo(name)
puts "Hello #{name}!"
Expand All @@ -181,9 +185,9 @@ end

####Returning from a function

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:
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'
Expand All @@ -198,7 +202,7 @@ end

Another example:

```
```ruby
def times_2(n):
n * 2 #Ruby will auto return this value without the return statement.
end
Expand All @@ -207,7 +211,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"
Expand All @@ -219,7 +223,7 @@ end
####Functions with an arbitrary number of arguments using splat (```*```)<a name="splat-arguments"></a>
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) { ... }
```
Expand All @@ -228,7 +232,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
Expand All @@ -241,14 +245,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
```
Expand All @@ -263,7 +267,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
Expand All @@ -274,7 +278,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)
Expand All @@ -284,15 +288,15 @@ 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"
```
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
Expand All @@ -303,13 +307,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);
});
Expand All @@ -322,7 +326,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)
Expand All @@ -333,7 +337,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
Expand Down
Loading

0 comments on commit 3f27a1f

Please sign in to comment.