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

JavascriptRuby
Naming convention for variables, functions, and methodscamelCasesnake_case
Naming convention for classesPascalCasePascalCase
Declaring variableslet 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 constantsconst 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 variablesDeclare 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 Statementsif (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 statementif (condition) doThis;do_this if condition
Ternary conditional expressioncondition ? doThisIfTrue : doThisIfFalse;condition ? do_this_if_true : do_this_if_false
Switch / case statementswitch(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 / methodfunction 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 objectthisself
Error handlingtry {
  // do something risky
} catch(err) {
  // handle error here
}
begin
   # do something risky
rescue
  # handle error here
end

2. Arrays & Strings

JavascriptRuby
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 block
end
– or –

(0..some_arr.length-1).each do |i|
  puts i, some_arr[i]
  # rest of block
end
Delete an element at index i of an arraysomeArray.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 arrayconst 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 arrayconst 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 arraysomeArray.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 ordersomeArray.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 ordersomeArray.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 Interpolationconsole.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 ConcatenationsomeString = ‘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 stringlet varString = someNum.toString();var_string = some_num.to_s
Convert a string to an integerlet varNum = Number(someString);var_num = some_string.to_i
Convert a string to a floatlet varNum = parseFloat(someString);var_num = some_string.to_f

3. Objects / Hashes

JavascriptRuby
Key-value pair data type is calledan objecta 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/hashsomeExistingObject[key3] = value3;

or

someExistingObject.key3 = value3;
some_existing_object[:key3] = value3
Iterate through an object/hash in one linefor(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 pairdelete someObject[someKey];some_hash.delete(some_key)
Check if an object/hash has a keysomeObject.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
Senior Engineer at Briefcat, LLC

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

comments powered by Disqus

Related