Syntax Differences Between Ruby and Javascript
Tags: syntax, ruby, javascript, languages
Published: 2020-09-01 21:44:42

This article originally appeared on [https://vahid.blog](https://vahid.blog)

I've been working with Javascript for a while now, and have gotten fairly comfortable with its syntax. 

I'm now also using Ruby again, which has a slightly different flavor. 

Here are some of the main syntactical differences between the two languages, in table format.

<br>

## 1. Basics

|  | Javascript | Ruby  |
| --- | --- | ---  |
| Naming convention for variables, functions, and methods | camelCase | snake_case |
| Naming convention for classes | PascalCase | PascalCase |
| Declaring variables | `let` someArray `= [`1,2`];` <br><br> Although `var` was exclusively used in older codebases, `let` is now more encouraged because `let` is block scoped while `var` is function scoped and can cause unintended consequences | some_array `= [`1,2`]` |
| Declaring constants | `const` SOMECONSTANT `= `3.14`;`<br><br>Reassigning something else to the constant will throw an error | SOME_CONSTANT `=` 3.14<br><br>Ruby will throw a warning when attempting to reassign something else to the constant, but will let you do it |
| Declaring global variables | Declare the variable with `let` or `const` in the global context. <br><br>However, if a variable with the same name is declared in a local scope, the local variable will be usable in that scope but not the global variable | You can declare a global variable anywhere by using a `$` just in front of the variable name<br><br> (e.g. `$`this_is_a_global_variable `=` 2100 ) |
| Comments | `//`this is a single-line comment in JS<br><br>`/*`<br> This is<br>a multi-line<br>comment<br>in JS<br> `*/` | `#`this is a single-line comment in Ruby<br><br>`=begin`<br>This is<br>a multi-line<br>comment<br>in Ruby<br>`=end`|
| Print to console (automatically adding new line) | `console.log(`'hello world'`);` | `puts` 'hello world' |
| Print to console (without new line) | `process.stdout.write(`'hello'`);` | `print` 'hello' |
| Conditional Statements | `if (`someCondition`) {` <br> &nbsp;&nbsp;`//`do this<br>&nbsp;&nbsp;`//`and this <br> `} else if (`someOtherCondition`) {`<br> &nbsp;&nbsp;`//`do this instead<br>` } else {`<br> &nbsp;&nbsp;`//`otherwise do this<br>` } ` | `if` some_condition <br> &nbsp;&nbsp;`#`do this <br> &nbsp;&nbsp;`#`and this <br>`elsif` some_other_condition <br> &nbsp;&nbsp;`#`do this instead <br>`else`<br> &nbsp;&nbsp;`#`otherwise do this<br>`end` |
| one-line conditional statement | `if (`condition`)` doThis`;` | do_this `if` condition |
| Ternary conditional expression | condition `?` doThisIfTrue `:` doThisIfFalse`;` |  condition `?` do_this_if_true `:` do_this_if_false |
| Switch / case statement | `switch(`expression`) {` <br>&nbsp;&nbsp; `case` x: <br>&nbsp;&nbsp;&nbsp;&nbsp;  `//` code block<br>&nbsp;&nbsp;&nbsp;&nbsp; `break;` <br>&nbsp;&nbsp;  `case` y:<br>&nbsp;&nbsp;&nbsp;&nbsp; // code block<br>&nbsp;&nbsp;&nbsp;&nbsp; `break;`<br> &nbsp;&nbsp;`default:` <br>&nbsp;&nbsp;&nbsp;&nbsp; `//` code block<br>`}` <br><br> If you do not `break`, JS will execute every line after that case too | `case` expression<br>&nbsp;&nbsp; `when` x <br>&nbsp;&nbsp;&nbsp;&nbsp;`#`code block <br>&nbsp;&nbsp; `when` y <br>&nbsp;&nbsp;&nbsp;&nbsp;`#`code block <br>&nbsp;&nbsp; `else`<br>&nbsp;&nbsp;&nbsp;&nbsp;`#`code block <br>`end` |
| Define a function / method | `function` someFunction`(`param1, param2`){`<br>&nbsp;&nbsp;`//`do stuff<br>&nbsp;&nbsp;`return` something;<br>`}`<br><br>If the `return` keyword is never used, the function will return `undefined` | `def` some_method`(`param1, param2`)`<br>&nbsp;&nbsp;`#`do stuff<br>&nbsp;&nbsp;`return` something<br>`end`<br><br>If the `return` keyword is never used, the method will return whatever is calculated on the last line before the `end` statement. |
| Keyword to refer to the current particular instantiated object | `this` | `self` |
| Error handling | `try {` <br> &nbsp;&nbsp;`//` do something risky <br> `} catch(err) {` <br>&nbsp;&nbsp;`//` handle error here <br> `}` | `begin` <br> &nbsp;&nbsp; `#` do something risky <br> `rescue` <br> &nbsp;&nbsp;`#` handle error here <br> `end` |


<br>

## 2. Arrays & Strings

|  | Javascript | Ruby |
| --- | --- | ---  |
| Map / Collect method <br>(Returning a new array of tweaked elements from an original array) | `const` newArray `=` someArray`.map(`el` =>` el * 2`)` | new_array `=` some_array`.map { |`el`|` el * 2 `}` <br><br> * To mutate the *original* array, use `map!` instead of `map` <br> * The `collect` method is the same as `map`|
| Iterate through an array's elements in one line and no need for index # | someArray.forEach(el => console.log(el)); | some_array.each { |el| puts el } |
| Iterate through an array's elements to perform a block requiring index # | for(let i=0; i < someArr.length; i++){<br>&nbsp;&nbsp;console.log(i, someArr[i]);<br> &nbsp;&nbsp;// rest of block<br>} | some_arr.each_index do |i|<br> &nbsp;&nbsp; puts i, some_arr[i]<br> &nbsp;&nbsp;# rest of block <br>end<br><center>-- or --</center><br> (0..some_arr.length-1).each do |i|<br> &nbsp;&nbsp;puts i, some_arr[i]<br> &nbsp;&nbsp;# rest of block <br>end |
| Delete an element at index i of an array | someArray.splice(i,length); <br><br> Where i=index # to start deleting, and <br>length = # of elements to delete | some_array.delete_at(i)<br><br> To delete all elements of a particular value (e.g. 'cat') regardless of index number, use:<br> some_array.delete('cat') |
| Return the unique values of an array | const uniqueArray = [...new Set(someArray)]; | unique_array = some_array.uniq <br><br> To mutate the *original* array and retain only its unique values, use:<br> someArray.uniq! |
| Filter an array | const filteredArray = someArray.filter(el => el > 5);<br><br>E.g. Returns all elements in someArray greater than 5 | filtered_array = some_array.select { |el| el > 5} <br><br>E.g. Returns all elements in some_array greater than 5 |
| Check if an element is in an array | someArray.includes(5); <br><br> E.g. Returns true if someArray has an element with a value of 5 | some_array.include?(5) <br><br> E.g. Returns true if some_array has an element with a value of 5 <br><br>For methods that return a boolean, a Ruby convention is to name them with a ? at the end |
| String Concatenation | someString = 'Hi,' + someName;<br><br> If the left side of the `+` is a string, then JS will coerce anything that appears on the right side into a string too, even if it's a number or another data type | some_string = 'Hi,' + some_name <br><br> Ruby will throw an error if you attempt to concatenate a string with a non-string. You must convert it to a string first (i.e. `.to_s`)|
| Convert a number to a string | `let` varString `=` someNum`.toString();` | var_string `=` some_num`.to_s` |
| Convert a string to an integer | `let` varNum `= Number(`someString`);` | var_num `=` some_string`.to_i` |
| Convert a string to a float | `let` varNum `= parseFloat(`someString`);` | var_num `=` some_string`.to_f` |

<br>

## 3. Objects / Hashes

|  | Javascript | Ruby |
| --- | --- | ---  |
| Key-value pair data type is called | an object | a hash |
| object/hash creation + assignment <br><br>(Literal notation) | `const` someObject `= {`key1`:` value1`,` key2`:` value2`};` | the older, symbol & hash-rocket method:<br>some_hash `= {:`key1 `=>` value1`, :`key2 `=>` value2`}`<br><br> or the newer, cleaner method: <br>some_hash `= {`key1`:` value1`,` key2`:` value2`}`<br> |
| Object/hash creation <br><br>(class instantiation notation) | `const` someObject `= new Object;` | some_hash `= Hash.new` |
| Add key/value pair to an existing object/hash | someExistingObject[key3] `=` value3`;` <br><br>or<br><br> someExistingObject.key3 `=` value3`;`| some_existing_object[`:`key3] `=` value3 | 
| Iterate through an object/hash in one line | for(let key in someObject) { console.log(key,someObject[key])};| some_hash.each { |key,value| puts key,value } <br><br> Using the `.each` method on a hash with only one parameter (e.g. |el|) would make that variable an array of two elements: the key at 0 (el`[0]`), and the value at 1 (el`[1]`) | 
| convert an object/hash to an array of sub-arrays of [key,value] | const someArray = `Object.entries(`someObject`);` |  some_array = some_hash.to_a |
| Delete a key/value pair | `delete` someObject[someKey]; | some_hash.delete(some_key) |
| Check if an object/hash has a key | someObject.hasOwnProperty(someKey) | some_hash.has_key?(some_key)<br><br><center>- or -</center><br><br>the `fetch` method allows you to get the value at the key or specify an alternative return value if the key doesn't exist:<br><br> some_hash.fetch(some_key, "error message") |