This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by adenaddis
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;
}
Lets jot down a couple things we see with js syntax
- Use starter keyword function to show the code is a function
- jsFunction is the variable name (we use this term to refer to the code wherever we please)
- NEED parentheses ( ) right after the variable name to place any parameters we might have in them.
- param is the variable name for the functions parameter that will be used when the function is later passing an argument and being invoked.
- Next, curly brackets { } is a MUST to indicate the body of the function
- console.log() is what will be displayed in the terminal
- 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
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
Lets see what makes ruby different:
- Use starter keyword def to show the code is a method
- 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.
- Parameters still come after the method name, parentheses are optional
- 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.
- 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
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
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by adenaddis
adenaddis | Sciencx (2022-09-16T17:14:16+00:00) Javascript vs Ruby: Syntax Edition. Retrieved from https://www.scien.cx/2022/09/16/javascript-vs-ruby-syntax-edition/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.