JavaScript vs. Ruby: Closing the Gap for Developers
Hey there! Are you a JavaScript or Ruby fan who wants to expand your programming skills? Well, you’re in luck! Join us for this awesome blog series where we’ll dive deep into the similarities and differences between these two kickass languages.
Language Basics and Core Concepts
Outline:
1. Introduction to JavaScript and Ruby
2. Data Types
3. String Interpolations
4. Type Casting
5. Inbuilt Methods
6. Strings as Arrays
7. Assignment Operations
8. Math Method
Introduction to JavaScript and Ruby
First things first, let’s get acquainted with JavaScript and Ruby. These two programming languages are widely used and have their own unique features and syntax.
JavaScript and Ruby are awesome high-level programming languages that are known for being super easy to use and super versatile. JavaScript is like a rockstar when it comes to creating dynamic web content, and you can use it on both the client-side and server-side with Node.js. It’s got support for multiple programming styles and a whole bunch of libraries and frameworks to play around with. Ruby, on the other hand, is all about elegance and readability. It’s perfect for web development, especially with Ruby on Rails. You can do object-oriented, functional, and imperative programming with Ruby, and it’s got this cool thing called Metaprogramming that makes it even more powerful. So, both of these languages have their own unique strengths that make them super valuable tools for today’s programmers.
Data Types
Now, let’s talk about data types. In both JavaScript and Ruby, you’ll be working with different types of data such as numbers, strings, booleans, and more. Understanding these data types is crucial for writing effective code.
let num = 42; //number both positive and negative.
let floatNum = 3.14; // for Decimal
let str = "Hello, World!"; //strings
let isTrue = true; //boolean
let emptyValue = null; //absence of any object value
let undefinedValue; //Been declared but not assigned a value
let arr = [1, 2, 3]; //collections of similar type of values i.e, string, int, etc.
let obj = { key: 'value' }; // collection of diffrent types, with unique value.
# doesn't need a initiaizer like JS.
num = 42 #number
float_num = 3.14 #decimal numbers
str = "Hello, World!" #string
is_true = true #boolean
empty_value = nil #This is for empty, undefined and null in JS
arr = [1, 2, 3] #Collection
hash = { key: 'value' } # Both are used for storing collections of key-value pairs.
String Interpolations
Next up, we have string interpolations. This handy feature allows you to embed variables or expressions inside strings. It’s a powerful way to create dynamic and flexible strings in your code.
let name = "Kota";
let age = 28;
// Using template literals for string interpolation
let greeting = `Hello, my name is ${name} and I am ${age} years of Age`;
console.log(greeting);
name = "Kota"
age = 28
# Using double-quoted strings for string interpolation
greeting = "Hello, my name is #{name} and I am #{age} years of Age."
puts greeting # Outputs: Hello, my name is Kota and I am 28 years of Age.
Type Casting
Type casting is another important concept to grasp. It involves converting one data type into another. You’ll learn how to convert strings to numbers and vice versa, which can be super useful in certain situations.
let str = "123";
let num = 10203;
let bool = true;
console.log(str); // Outputs: "123"
console.log(typeof str); // Outputs: string
let strFromNum = Number(str);
console.log(str); // Outputs: 123
console.log(typeof str); // Outputs: number
let numParse = parseInt("123.45");
console.log(numParse); // Outputs: 123
let floatNum = parseFloat("123.45");
console.log(floatNum); // Outputs: 123.45
let numStr = String(num);
console.log(numStr); // Outputs: "10203"
console.log(typeof numStr); // Outputs: string
let numStr2 = num.toString();
console.log(numStr2);// Outputs: "10203"
let boolenStr = String(bool);
console.log(boolenStr); // Outputs: "true"
let boolenNum = Number(bool);
console.log(boolenNum); // Outputs: 1
boolenStr = Boolean(str);
console.log(boolenStr); // Outputs: true (non-empty strings are truthy)
str = "123"
float_str = "123.45"
puts str # Outputs: "123"
puts str.class # Outputs: String
num = str.to_i
puts num # Outputs: 123
puts num.class # Outputs: Integer
float_num = float_str.to_f
puts float_num # Outputs: 123.45
puts float_num.class # Outputs: Float
float_num = 123.45
float_str = float_num.to_s
puts float_str # Outputs: "123.45"
puts float_str.class # Outputs: String
bool = true
str = bool.to_s
puts str # Outputs: "true"
num = bool ? 1 : 0
puts num # Outputs: 1
Ruby: Uses methods like to_i
, to_f
, to_s
for type casting.
JavaScript: Uses Number()
, String()
, Boolean()
, parseInt()
, and parseFloat()
for type casting.
**Handling Non-Numeric Strings => JS: Number("abc")
returns NaN
,Ruby: "abc".to_i
returns 0
.
Inbuilt Methods
Both JavaScript and Ruby come with a bunch of inbuilt methods that make your life easier. These pre-defined functions can perform various operations on strings, numbers, arrays, and more. We’ll show you how to make the most of them.
let str = "Hello, World!";
// Length of the string
console.log(str.length); // Outputs: 13
// Convert to uppercase
console.log(str.toUpperCase()); // Outputs: "HELLO, WORLD!"
// Convert to lowercase
console.log(str.toLowerCase()); // Outputs: "hello, world!"
// Find the position of a substring
console.log(str.indexOf("World")); // Outputs: 7
// Replace a substring
console.log(str.replace("World", "JavaScript")); // Outputs: "Hello, JavaScript!"
// Extract a substring
console.log(str.substring(0, 5)); // Outputs: "Hello"
// Number Methods
let num = 123.456;
// Convert to fixed-point notation
console.log(num.toFixed(2)); // Outputs: "123.46"
// Convert to exponential notation
console.log(num.toExponential(2)); // Outputs: "1.23e+2"
// Parse a string to an integer
console.log(Number.parseInt("123")); // Outputs: 123
// Parse a string to a float
console.log(Number.parseFloat("123.456")); // Outputs: 123.456
// Array Implementation
let arr = [1, 2, 3, 4, 5];
// Length of the array
console.log(arr.length); // Outputs: 5
// Add an element to the end
arr.push(6);
console.log(arr); // Outputs: [1, 2, 3, 4, 5, 6]
// Remove an element from the end
arr.pop();
console.log(arr); // Outputs: [1, 2, 3, 4, 5]
// Add an element to the beginning
arr.unshift(0);
console.log(arr); // Outputs: [0, 1, 2, 3, 4, 5]
// Remove an element from the beginning
arr.shift();
console.log(arr); // Outputs: [1, 2, 3, 4, 5]
// Find the index of an element
console.log(arr.indexOf(3)); // Outputs: 2
// Check if an array includes an element
console.log(arr.includes(4)); // Outputs: true
str = "Hello, World!"
# Length of the string
puts str.length # Outputs: 13
# Convert to uppercase
puts str.upcase # Outputs: "HELLO, WORLD!"
# Convert to lowercase
puts str.downcase # Outputs: "hello, world!"
# Find the position of a substring
puts str.index("World") # Outputs: 7
# Replace a substring
puts str.sub("World", "Ruby") # Outputs: "Hello, Ruby!"
# Extract a substring
puts str[0, 5] # Outputs: "Hello"
# Number Implementation.
num = 123.456
# Round the number
puts num.round(2) # Outputs: 123.46
# Convert to integer
puts num.to_i # Outputs: 123
# Convert to string
puts num.to_s # Outputs: "123.456"
# Array implementations
arr = [1, 2, 3, 4, 5]
# Length of the array
puts arr.length # Outputs: 5
# Add an element to the end
arr.push(6)
puts arr.inspect # Outputs: [1, 2, 3, 4, 5, 6]
# Remove an element from the end
arr.pop
puts arr.inspect # Outputs: [1, 2, 3, 4, 5]
# Add an element to the beginning
arr.unshift(0)
puts arr.inspect # Outputs: [0, 1, 2, 3, 4, 5]
# Remove an element from the beginning
arr.shift
puts arr.inspect # Outputs: [1, 2, 3, 4, 5]
# Find the index of an element
puts arr.index(3) # Outputs: 2
# Check if an array includes an element
puts arr.include?(4) # Outputs: true
Strings as Arrays
Did you know that in both JavaScript and Ruby, you can treat strings as arrays? This means you can access individual characters or manipulate strings using array-like syntax. It’s a nifty trick that can come in handy.
let str = "Hey Kota!";
// Access individual characters
console.log(str[0]); // Outputs: "H"
console.log(str.charAt(7)); // Outputs: "a"
console.log(str.replace("ey", "ello")); //Hello Kota!
str = "Hey Kota!"
# Access individual characters
puts str[0] # Outputs: "H"
puts str[7] # Outputs: "W"
console.log(str.gsub("ey", "ello")); ##Hello Kota!
Assignment Operations
Time to talk about assignment operations. These are the building blocks of programming. We’ll cover how to assign values to variables, perform arithmetic operations, and update variables using shortcuts.
let a = 5;
let b = 10;
// Basic assignment
let sum = a + b; // sum = 15
// Compound assignment
a += 3; // Equivalent to a = a + 3; (a becomes 8)
b -= 4; // Equivalent to b = b - 4; (b becomes 6)
a *= 2; // Equivalent to a = a * 2; (a becomes 16)
b /= 2; // Equivalent to b = b / 2; (b becomes 3)
console.log(a, b); // Outputs: 16 3
a = 5
b = 10
# Basic assignment
sum = a + b # sum = 15
# Compound assignment
a += 3 # Equivalent to a = a + 3; (a becomes 8)
b -= 4 # Equivalent to b = b - 4; (b becomes 6)
a *= 2 # Equivalent to a = a * 2; (a becomes 16)
b /= 2 # Equivalent to b = b / 2; (b becomes 3)
puts "#{a} #{b}" # Outputs: 16 3
Assignment operations in both languages follow similar syntax and behavior, making it easy to understand and transition between the two languages.
Math Method
Last but not least, let’s explore some math methods. JavaScript and Ruby provide a range of math functions that allow you to perform calculations, round numbers, find square roots, and more. We’ll walk you through them.
// Absolute value
console.log(Math.abs(-5)); // Outputs: 5
// Maximum value
console.log(Math.max(1, 2, 3)); // Outputs: 3
// Minimum value
console.log(Math.min(1, 2, 3)); // Outputs: 1
// Power
console.log(Math.pow(2, 3)); // Outputs: 8
// Square root
console.log(Math.sqrt(16)); // Outputs: 4
// Random number between 0 and 1
console.log(Math.random()); // Outputs a random number between 0 and 1
# Absolute value
puts (-5).abs # Outputs: 5
# Maximum value
puts [1, 2, 3].max # Outputs: 3
# Minimum value
puts [1, 2, 3].min # Outputs: 1
# Power
puts 2**3 # Outputs: 8
# Square root
puts Math.sqrt(16) # Outputs: 4
# Random number between 0 and 1
puts rand # Outputs a random number between 0 and 1
Conclusion:
Stay tuned for our next installment, where we’ll take a deep dive into control structures and loops. Whether you’re coding in JavaScript or Ruby, our series will help you navigate the ins and outs and level up your programming skills. Don’t miss out on this journey to becoming a more versatile developer!