Ruby vs. Javascript
Tale of Two Languages
Ruby and Javascript are very difference languages in many ways such as their syntax, methods, and ways of defining functions. Ruby tends to be shorter and more compact but javascript seems to be more explicit in defining their values such as putting function(), and var in front of the object. Both are object oriented programming languages, where they have a class and objects and methods that associates with them are organized in a proper way.
Functions
Javascript has two ways of defining functions
- function expressions
- function declarations
Here is a function declaration
1 2 3 |
|
Here is a function expression
1 2 3 |
|
Ruby on the other hand, has three types of functions
- blocks
- procs
- lambdas
Here is a block
1
|
|
Here is a proc
1 2 |
|
Here is a lambda
1 2 |
|
Procs and lambdas seem to be closer to a function expression in javascript, because you can set a block to a variable and then call it later.
Iterations
In Ruby:
1 2 3 4 |
|
In Javascript:
1 2 3 4 |
|
In this way, javascript seems to be more explicit in showing the types of each element of the method. Javascript specifies var for the variable, and also it lists out the variable to start iteration, the condition for the loop to run, and what happens after each iteration.
Since ruby and javascript are quite different they also have similar methods, that are sometimes called different things but mean the same thing.
Ruby | Javascript |
---|---|
push | push |
reverse | reverse |
map | map |
index | indexOf |
all? | every |
any? | some |
slice | slice |
each | forEach |
index | indexOf |
split | split |
has_key? | hasOwnProperty |
to_i | parseInt |
.class | typeof() |
Methods that do not exist in Javascript:
- include?
Other Comparisons:
Ruby | Javascript |
---|---|
puts | console.log() |
nil, false | 0, null, false, “”, undefined, NaN |
Return is usually used in Javascript, but not in Ruby, because Ruby returns the value of the last line in the method. Javascript will not return it without it explicitly being called return.
Arrays
1 2 3 4 5 |
|
Hashes
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Functions
1 2 3 4 5 6 7 8 9 |
|
Classes
Javascript’s equivalent to Ruby’s class is called a Prototype. To make a new Prototype, just create a new function with a name with aguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Math
1 2 3 4 5 |
|