DEV Community

Vahid Dejwakh
Vahid Dejwakh

Posted on

Syntax Differences Between Ruby and Javascript

This article originally appeared on 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.

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 {
Iterate through an array's elements in one line and no need for index # someArray.forEach(el => console.log(el)); some_array.each {
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
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 {
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
String Concatenation someString = 'Hi,' + someName;

If the left side of the {% raw %}+ 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 {
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")

Top comments (1)

Collapse
 
boseriko profile image
Bos Eriko Reyes

this deserves more views from the full stack javascript/ruby developers. I wanted to create an app about this but you already have a good post about it. thanks!