Syntax differences between Ruby and Javascript

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.
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]; 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; Reassigning something else to the constant will throw an error | SOME_CONSTANT = 3.14Ruby 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.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(e.g. $ this_is_a_global_variable = 2100 ) |
Comments | // this is a single-line comment in JS/* This is a multi-line comment in JS */ | # this is a single-line comment in Ruby=begin This is a multi-line comment in Ruby =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) { // do this// and this} else if ( someOtherCondition) { // do this instead} else { // otherwise do this} | if some_condition# do this# and thiselsif some_other_condition# do this insteadelse # otherwise do thisend |
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) { case x:// code blockbreak; case y:// code block break; default: // code block} If you do not break , JS will execute every line after that case too | case expressionwhen x# code blockwhen y# code blockelse # code blockend |
Define a function / method | function someFunction( param1, param2){ // do stuffreturn something;} If the return keyword is never used, the function will return undefined | def some_method( param1, param2) # do stuffreturn somethingend 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 { // do something risky} catch(err) { // handle error here} | begin # do something riskyrescue # handle error hereend |
2. Arrays & Strings
Javascript | Ruby | |
---|---|---|
Map / Collect method (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 } * To mutate the original array, use map! instead of map * 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++){ console.log(i, someArr[i]); // rest of block} | some_arr.each_index do | i| puts i, some_arr[i] # rest of blockend ( 0.. some_arr.length-1).each do | i| puts i, some_arr[i] # rest of blockend |
Delete an element at index i of an array | someArray.splice( i, length); Where i=index # to start deleting, and length = # of elements to delete | some_array.delete_at( i) To delete all elements of a particular value (e.g. ‘cat’) regardless of index number, use: some_array .delete( 'cat') |
Return the unique values of an array | const uniqueArray = [...new Set( someArray)]; | unique_array = some_array.uniq To mutate the original array and retain only its unique values, use: someArray .uniq! |
Filter an array | const filteredArray = someArray.filter( el => el > 5); E.g. Returns all elements in someArray greater than 5 | filtered_array = some_array.select { | el| el > 5} E.g. Returns all elements in some_array greater than 5 |
Check if an element is in an array | someArray.includes( 5); E.g. Returns true if someArray has an element with a value of 5 | some_array.include?( 5) E.g. Returns true if some_array has an element with a value of 5 For methods that return a boolean, a Ruby convention is to name them with a ? at the end |
Sorting an array in Ascending order | someArray.sort((a,b)=>a-b) This mutates the original array | some_arr.sort This does not mutate the original array. To do that, use .sort! instead |
Sorting an array in Descending order | someArray.sort((a,b)=>b-a) This mutates the original array | some_arr.sort { |a, b| b <=> a } This does not mutate the original array. To do that, use .sort! instead |
Template Literals / String Interpolation | console.log(` Welcome onboard, ${ someName}`); The use of backticks are required for template literals. | puts ` Welcome onboard, #{ some_name}` You can use backticks, or double quotes (but not single quotes) |
String Concatenation | someString = ‘Hi,’ + someName; 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_nameRuby 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 |
3. Objects / Hashes
Javascript | Ruby | |
---|---|---|
Key-value pair data type is called | an object | a hash |
object/hash creation + assignment (Literal notation) | const someObject = { key1: value1, key2: value2}; | the older, symbol & hash-rocket method: some_hash = {: key1 => value1, : key2 => value2} or the newer, cleaner method: some_hash = { key1: value1, key2: value2} |
Object/hash creation (class instantiation notation) | const someObject = new Object; | some_hash = Hash.new |
Add key/value pair to an existing object/hash | someExistingObject[key3] = value3; or 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 } 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) the fetch method allows you to get the value at the key or specify an alternative return value if the key doesn’t exist:some_hash .fetch( some_key, “error message") |