Skip to content

c0x6a/python-vs-ruby-vs-javascript

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 

Repository files navigation

Table of Contents

Data Types

Strings

Mutating strings

In Python, Strings are immutable.

s = "Sun"
s[0] = "F" # => TypeError: 'str' object does not support item assignment

In Ruby, Strings are mutable.

s = "Sun"
s[0] = "F"
s #=> Fun

In JavaScript, Strings are immutable.

let s2 = "Sun";
s2[0] = "F"; // The action is not performed but no error is triggered
console.log(s2[0]); // Sun

Interpolating strings

In Python

q = "quick"
f"The {q} brown box"

In Ruby

q = "quick"
"The #{q} brown box"

In JavaScript

q = "quick";
`The #{q} brown box`;

Slicing strings

In Python, we use the [] function, passing in three params:

  1. Start index
  2. End index (which is excluded)
  3. Stepper
s = "abcdefghijk"
s[0:3]  # From index 0 to 3 (exclusive) => "abc"
s[:3]   # From the start to index 3 (exclusive) => "abc"
s[1:]   # From index 1 to the end => "bcdefghijk"
s[::2]  # From the start to the end in steps of 2 => "acegik"

In Ruby, we use the slice function, passing two params:

  1. Start index
  2. Number of chars you want to take
s = "abcdefghijk"
s.slice(0,3)  # From 0, take the 3 first chars => "abc"

Alternatively, you can pass a range (considering the end index is included)

s = "abcdefghijk"
s[0..3] # From index 0 to 3 (inclusive) => "abcd"

Or a regex, with an optional capture group

s = "abcdefghijk"
s[/[aeiou]/]      #=> "a"

In JavaScript, we use the slice function, passing two params:

  1. Start index
  2. End index (which is excluded)
s = "abcdefghijk"
s.slice(0,3) # From index 0 to 3 (exclusive) => "abc"

Reversing strings

In Python

s[::-1] # From the start to the end in steps of 1, counting backwards => "kjihgfedcba"

In Ruby

s.reverse #=> "kjihgfedcba"

In JavaScript

There's no built-in method to do this.

Capitalizing strings

In Python

s.upper()
s.lower()

In Ruby

s.upcase
s.downcase

In JavaScript

s.toUpperCase();
s.toLowerCase();

Integers

In Python

1 / 2 #=> 0.5 True Division

In Ruby

1 / 2 #=> 0 Integer Division
1.0 / 2.0 #=> 0.5 Float Division

In JavaScript

1 / 2; //=> 0.5 True Division

Booleans

In Python

True
False

In Ruby

true
false

In JavaScript

true;
false;

None (Python), nil (Ruby), null (JavaScript)

In Python

None

In Ruby

nil

In JavaScript

null;

Truthyness

For quick reference:

Python Ruby JavaScript
None/nil/null
""
[]

In Python

not(not(None)) #=> False
not(not("")) #=> False
not(not([])) #=> False

In Ruby

!!nil #=> False
!!"" #=> True
!![] #=> True

In JavaScript

!!null; //=> False
!!""; //=> False
!![]; //=> True

Operators

Equality

In Python and Ruby we use strict equality.

==

In JavaScript we have two distinct operators for abstract and strict equality. See MDN for more details.

== // Abstract equality comparison (compares values after converting them to the same type)
=== // Strict equality comparison

Boolean

In Python we use:

and
or
not

Note the &&, || and ! boolean operators are not available in Python.

In Ruby we use:

&&
||
!

Note that though the and, or and not operators are available in Ruby, they are better suited as control flow operators. If we choose to use them as boolean operators (which is against general advice), we must be aware of the fact that they have a lower precedence than their counterparts (&&, || and !).

In Javascript we use:

&&
||
!

Note the and, or and not operators are not available in JavaScript.

Relational

These work in the same way in all three languages.

>
<
>=
<=

Data Structures

Lists (Python) / Arrays (Ruby and JavaScript)

Creating a list

In Python

my_list = ['a', 'b', 'c']

In Ruby

my_list = ['a', 'b', 'c']

In JavaScript

const myList = ["a", "b", "c"];

Adding an item

In Python

my_list.append('d')

In Ruby

my_list.push('d')

In JavaScript

myList.push("d");

Removing items

In Python

my_list.pop()
my_list.pop(1) #=> "b" Removes and returns the element at index 1

In Ruby

my_list.pop()
my_list.pop(2) #=> ["b", "c"] Removes and returns as many items as indicated, in this case 2 items

In JavaScript

myList.pop();
myList.pop(1); //=> "b" Removes and returns the element at index 1

Counting items

In Python

len(my_list)

In Ruby

my_list.length

In JavaScript

myList.length();

Getting the minimum and maximum items

In Python

min([1, 2, 3])
max([1, 2, 3])

In Ruby

[1, 2, 3].min
[1, 2, 3].max

In JavaScript

Math.min(...[1, 2, 3]);
Math.max(...[1, 2, 3]);

Checking for the inclusion of an item

In Python

1 in [1, 2, 3]

In Ruby

[1, 2, 3].include?(1)

In JavaScript

[1, 2, 3].includes(1);

Sorting items

In Python

my_list.sort() # Sorts the list in place, doesn't return anything

In Ruby

my_list.sort # Sorts
my_list.sort! # Sorts the list in place

In JavaScript

myList.sort(); // Sorts the list in place, and returns it

Reversing items

In Python

my_list.reverse() # Reverses the list in place, doesn't return anything

In Ruby

my_list.reverse # Reverses
my_list.reverse! # Reverses the list in place

In JavaScript

myList.reverse(); // Reverses the list in place, and returns it

Zipping lists/arrays together

In Python

a = [1, 2, 3]
b = ["a", "b", "c"]

for item in zip(a, b):
    print(item)

# (1, 'a')
# (2, 'b')
# (3, 'c')

In Ruby

a = [1, 2, 3]
b = %w[a b c]

a.zip(b).each do |item|
  puts item
end

# 1
# a
# 2
# b
# 3
# c

In JavaScript

There's no built-in method to do this.

Comprehending Lists

In Python

new_list = [some_method(i) for i in old_list if condition_method(i)]

In Ruby and JavaScript, there's no built-in method to do this.

Ranges

In Python

range(10) # From 0 to 10 (exclusive) => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(0, 10) # From 0 to 10 (exclusive)
range(0, 10, 2) # From 0 to 10, in steps of 2 => [0, 2, 4, 6, 8]

To convert ranges to lists, we do list(range(0,10)).

In Ruby

0..10 # From 0 to 10 (inclusive) => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0...10 # From 0 to 10 (exclusive) => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To convert ranges to arrays, we do (0..10).to_a.

In JavaScript

There's no built-in method to create ranges.

Sets

In Python

Sets are unordered collections of unique values.

my_set = set()
my_set.add(1) # {1}
my_set.add(2) # {1,2}
my_set.add(2) # {1,2}

In Ruby

In order to use them, the Set module needs to be required.

require 'set'
my_set = Set[]
my_set.add(1)
my_set.add(2)
my_set.add(2)

In JavaScript

mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2);

Tuples

In Python

Tuples, unlike lists, are immutable, to ensure elements don't get flipped or reassigned.

my_tuple = ('a', 'a', 'b')
my_tuple.index('a')
my_tuple.count('a')

In Ruby and JavaScript, there's no concept of tuples.

Named tuples

In Python

color = (red=255, green=0, blue=0)

In Ruby, there's no concept of named tuples, however, Struct or OpenStruct could be used as alternatives.

require 'ostruct'

Color = Struct.new(:red, :green, :blue)
color = Color.new(255, 0, 0)

In JavaScript, there's no concept of named tuples, object literals are used instead.

const color = { red: 255, green: 0, blue: 0 };

Dictionaries (Python) / Hashes (Ruby) / objects (JavaScript)

In Python

my_dict = {
  'apple': 2.99,
  'oranges': 1.99,
  'watermelon': 0.5
}
my_dict['apple']
my_dict.get('banana', 2.5) # Augments the method above, providing a default value
my_dict.keys()
my_dict.values()
my_dict.items() # Converts the dictionary into a list

In Ruby

my_hash = {
  apple: 2.99,
  oranges: 1.99,
  watermelon: 0.5
}
my_hash[:apple]
my_hash.fetch(:banana, 2.5) # Augments the method above, providing a default value
my_hash.keys
my_hash.values
my_hash.to_a # Converts the hash into an array

In JavaScript

myObj = {
  apples: 2.99,
  oranges: 1.99,
  watermelon: 0.5,
};
myObj.apple;
Object.keys(myObj);
Object.values(myObj);
Object.entries(myObj);

Checking for the inclusion of a key

In Python

"a" in {"a": 1}

In Ruby

{ a: 1 }.key?(:a)

In JavaScript

"a" in { a: 1 };

Statements

If

In Python

if True:
    print("✅")
elif True:
    print("❌")
else:
    print("❌")

In Ruby

if true
  puts('✅')
elsif true
  puts('❌')
else
  puts('❌')
end

In JavaScript

if (true) {
  console.log("✅");
} else if (true) {
  console.log("❌");
} else {
  console.log("❌");
}

Ternary if

In Python

"✅" if True else "❌"

In Ruby and JavaScript

true ? "✅" : "❌"

Switch

In Python

Switch statements are not available.

In Ruby

location = 'Beach'

case location
when 'Beach'
  puts 'Flip flops'
when 'Home'
  puts 'Chewbacca slippers'
when 'Mountain', 'Jungle'
  puts 'Boots'
else
  puts 'Sneakers'
end

In JavaScript

const location = "Beach";

switch (location) {
  case "Beach":
    console.log("Flip flops");
    break;
  case "Home":
    console.log("Chewbacca slippers");
    break;
  case "Mountain":
  case "Jungle":
    console.log("Boots");
    break;
  default:
    console.log("Sneakers");
}

For

Iterating over lists/arrays

In Python

for char in ["a", "b", "c"]:
    print(char)

In Ruby

%w[a b c].each do |char|
  puts char
end

In JavaScript

for (char of ["a", "b", "c"]) {
  console.log(char);
}

Iterating with an index over lists/arrays

In Python

for index, char in enumerate(["a", "b", "c"]):
    print(f"index: {index}, char: {char}")

In Ruby

%w[a b c].each_with_index do |char, index|
  puts "index: #{index}, char: #{char}"
end

In JavaScript

for ([index, char] of ["a", "b", "c"].entries()) {
  console.log(`index: ${index}, char: ${char}`);
}

Iterating over dictionaries/hashes/objects

In Python

my_dict = {"a": 1, "b": 2, "c": 3}

for k, v in my_dict.items():
    print(f"k:{k}, v:{v}")

In Ruby

my_hash = { a: 1, b: 2, c: 3 }

my_hash.each do |k, v|
  puts "k: #{k}, v: #{v}"
end

In JavaScript

const myObject = { a: 1, b: 2, c: 3 };

for (const k in myObject) {
  console.log(`k:${k}, v:${myObject[k]}`);
}

While

In Python

x = 0

while x < 11:
    print(x)
    x += 1
else:
    print("Stop")

In Ruby

x = 0

while x < 11
  puts x
  x += 1
end

In JavaScript

let n = 0;

while (n < 11) {
  console.log(n);
  n++;
}

Break

Breaks out of the closest enclosing loop. The same break keyword is used in all three languages.

Continue/Next

Skips the rest of the current iteration and goes to the top of the closeset enclosing loop.

In Python

continue

In Ruby

next

In JavaScript

continue;

Utilities

I/O to Files

In Python

file = open("/path/to/my/file.txt")
file.read() # Returns a single string with all the contents
file.readlines() # Returns an list, where each item is a line
file.write("Hi there!")
file.close()

Alternatively, to avoid having to close the file we can do:

with open("file.txt") as file:
  contents = file.read()
  file.write("Hi again!")

In Ruby

file = File.open("/path/to/my/file.txt")
file.read
file.readlines
file.write("Hi there!")
file.close

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors