Syntax differences between Ruby and Javascript

courtesy: unsplash.com

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.14

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.

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 this
elsif some_other_condition
  #do this instead
else
  #otherwise do this
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) {
   case x:
     // code block
     break;
   case y:
     // code block
     break;
  default:
     // code block
}

If you do not break, JS will execute every line after that case too
case expression
   when x
    #code block
   when y
    #code block
   else
    #code block
end
Define a function / method function someFunction(param1, param2){
  //do stuff
  return something;
}

If the return keyword is never used, the function will return undefined
def some_method(param1, param2)
  #do stuff
  return something
end

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 risky
rescue
  # handle error here
end

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}<br><br> * To mutate the *original* array, usemap!instead ofmap<br> * Thecollectmethod is the same asmap`
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 <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);

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 } <br><br>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_name

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

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}<br><br> Using the.eachmethod 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)

- or -


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”)
Vahid Dejwakh
Vahid Dejwakh
Software Engineer at Microsoft;
Co-Creator of the Fjord Framework

Vahid writes about interesting ideas at the intersection of software, system design, data, philosophy, psychology, policy, and business. He enjoys coffee and has a palate for spicy and diverse foods.

comments powered by Disqus

Related