Skip to content

Instantly share code, notes, and snippets.

@Martin-Alexander
Last active May 4, 2020 17:36
Show Gist options
  • Save Martin-Alexander/4ed3bac5cad5bf01f11d3d938f961d24 to your computer and use it in GitHub Desktop.
Save Martin-Alexander/4ed3bac5cad5bf01f11d3d938f961d24 to your computer and use it in GitHub Desktop.

Comparisons Between Ruby and JavaScript

Iterating through over an array and printing each element

Ruby:

my_array = ["first_element", "second_element", "third_element"]

my_array.each do |element|
  puts element
end

JavaScript:

const myArray = ["firstElement", "secondElement", "thirdElement"];

myArray.forEach((element) => {
  console.log(element);
});

Iterating through over an object and printing each key/value pair

Ruby:

person = {
  name: "John",
  last_name: "Doe",
  age: 35,
  height: 178
}

person.each do |key, value|
  puts "#{key}: #{value}"
end

JavaScript:

const person = {
  name: "John",
  lastName: "Doe",
  age: 35,
  height: 178
};

Object.keys(person).forEach((key) => {
  const value = person[key];
  console.log(`${key}: ${value}`);
});

Else/If statements

Ruby:

age = 15

if age > 17
  puts "You are an adult"
elsif age > 12
  puts "You are a teenager"
else
  puts "You are neither a teenager nor an adult"
end

JavaScript:

const age = 15;

if (age > 17) {
  console.log("You are an adult");
} else if (age > 12) {
  console.log("You are a teenager");
} else {
  console.log("You are neither a teenager nor an adult");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment