DEV Community

Cover image for Javascript vs Ruby: Syntax Edition
adenaddis
adenaddis

Posted on

Javascript vs Ruby: Syntax Edition

Transitioning from consistently working with javascript to moving straight into ruby might be difficult due to adjusting our eyes to look at a new way of writing code and with that changing our habits.

Lets start simple...

Javascript Syntax

function jsFunction(param) {
  console.log("Look how Im written");
  return param + 5;
}
Enter fullscreen mode Exit fullscreen mode

Lets jot down a couple things we see with js syntax

  1. Use starter keyword function to show the code is a function
  2. jsFunction is the variable name (we use this term to refer to the code wherever we please)
  3. NEED parentheses ( ) right after the variable name to place any parameters we might have in them.
  4. param is the variable name for the functions parameter that will be used when the function is later passing an argument and being invoked.
  5. Next, curly brackets { } is a MUST to indicate the body of the function
  6. console.log() is what will be displayed in the terminal
  7. return is different in which it is not specifically for the terminal. We use this so that our function can have a return value when it is called on. For this example we have param plus 5.

How to check function !

const jsFunctionReturnValue = jsFunction(3);
// => ""Look how Im written"
console.log(myFunctionReturnValue);
// => 8
Enter fullscreen mode Exit fullscreen mode

Above we just called the jsFunction and passed an argument of 3 and assigned that to a variable called jsFunctionReturnValue. This in turn displays my earlier console.log in the terminal. When I console.log the new variable I made, I get the number 8 due to the 3 + 5.

Ruby Syntax

def rb_method(param)
  puts "Look how Im_written"
  param + 5
end
Enter fullscreen mode Exit fullscreen mode

Lets see what makes ruby different:

  1. Use starter keyword def to show the code is a method
  2. We use snake case for the variable name of the method. This just means the words are separated by an underscore (_). While JS uses camel case.
  3. Parameters still come after the method name, parentheses are optional
  4. Since we don't need curly braces here like in js, we use the keyword end after the code to identify where the code finishes.
  5. The return keyword is not needed in Ruby but you can use it. It is just known to ruby that the last line will the the return value.

Now to check Ruby code, you need to run IRB and put your previous code, press enter then check with the following:

rb_method_return_value = rb_method(10)
# Look how Im_written
# => 15
rb_method_return_value
# => 15
Enter fullscreen mode Exit fullscreen mode

Here we can see the argument of 10 being passed into our method and being assigned to a new variable which then we can call on and we get 15 because of 10 + 5.

Fun fact

jsrb

Top comments (0)