I’ve mostly been using Ruby to write code, but got to thinking how are the very bare bone basics different and or similar in Ruby, compared to JavaScript. Here are the comparisons, and contrasts with writing the basics variables, methods, arrays, and objects(hashes in Ruby).
First we’ll start with how assigning variables works. In JavaScript variables have to be declared with var or let. Whereas in Ruby variables can be written out without being declared. Another difference is that in JavaScript we use camel-case for variable names while in ruby we use snake-case. when declaring a constant variable in JavaScript we have to put a const. In Ruby to create a constant variable you use all caps. JavaScript also requires semicolons (;) to close out variables, parentheses are everywhere, and return isn’t implicit. Ruby doesn’t need semicolons, and parenthesis aren’t all that popular.
There are also similarities for example the basics of writing, string concatenations, arrays, methods/functions, hashes/objects, loops is nearly identical in the languages, and string interpolation is very very similar. The only difference being syntax.
JavaScript variables:
var firstName = "John";
let lastName = "Doe";
JS String Concatenation:
"First name " + firstName + " " + lastName ".";
JS String Interpolation:
String Interpolation requires backticks ``:`My first name is ${firstName}. My last name is ${lastName}`;
JS Arrays:
let sportsTeams = ["Lakers","Dodgers","Raiders"];
JS Functions:
function addNum(num1,num2){
let num3 = num1 + num2;
return num3;}
console.log(addNum(1,2)); //prints 3
JS Objects:
let car = {
make: "Toyota",
model: "Camry",
year: 1991,
color: "Faded"};
Ruby Variables:
first_name = "John"
last_name = "Doe"
Ruby String Concatenation:
my_name + last_name # "John Doe"
Ruby String Interpolation:
age = 40
first_name = "John""Hello, my name is, #{first_name}, my age is #{age}"
Ruby Arrays:
array = [1,2,3]
Ruby Methods:
def add(num1,num2)
num3 = num1 + num2
num3endputs add(1,2) #3
Ruby Hashes:
states = {
"California" => "CA",
"Oregon" => "OR",
"Washington" => "WA"}