- Data Types
- Truthyness
- Operators
- Data Structures
- Utilities
In Python, Strings are immutable.
s = "Sun"
s[0] = "F" # => TypeError: 'str' object does not support item assignmentIn Ruby, Strings are mutable.
s = "Sun"
s[0] = "F"
s #=> FunIn JavaScript, Strings are immutable.
let s2 = "Sun";
s2[0] = "F"; // The action is not performed but no error is triggered
console.log(s2[0]); // SunIn Python
q = "quick"
f"The {q} brown box"In Ruby
q = "quick"
"The #{q} brown box"In JavaScript
q = "quick";
`The #{q} brown box`;In Python, we use the [] function, passing in three params:
- Start index
- End index (which is excluded)
- 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:
- Start index
- 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:
- Start index
- End index (which is excluded)
s = "abcdefghijk"
s.slice(0,3) # From index 0 to 3 (exclusive) => "abc"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.
In Python
s.upper()
s.lower()In Ruby
s.upcase
s.downcaseIn JavaScript
s.toUpperCase();
s.toLowerCase();In Python
1 / 2 #=> 0.5 True DivisionIn Ruby
1 / 2 #=> 0 Integer Division
1.0 / 2.0 #=> 0.5 Float DivisionIn JavaScript
1 / 2; //=> 0.5 True DivisionIn Python
True
FalseIn Ruby
true
falseIn JavaScript
true;
false;In Python
NoneIn Ruby
nilIn JavaScript
null;For quick reference:
| Python | Ruby | JavaScript | |
|---|---|---|---|
None/nil/null |
❌ | ❌ | ❌ |
"" |
❌ | ✅ | ❌ |
[] |
❌ | ✅ | ✅ |
In Python
not(not(None)) #=> False
not(not("")) #=> False
not(not([])) #=> FalseIn Ruby
!!nil #=> False
!!"" #=> True
!![] #=> TrueIn JavaScript
!!null; //=> False
!!""; //=> False
!![]; //=> TrueIn 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 comparisonIn Python we use:
and
or
notNote 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.
These work in the same way in all three languages.
>
<
>=
<=In Python
my_list = ['a', 'b', 'c']In Ruby
my_list = ['a', 'b', 'c']In JavaScript
const myList = ["a", "b", "c"];In Python
my_list.append('d')In Ruby
my_list.push('d')In JavaScript
myList.push("d");In Python
my_list.pop()
my_list.pop(1) #=> "b" Removes and returns the element at index 1In Ruby
my_list.pop()
my_list.pop(2) #=> ["b", "c"] Removes and returns as many items as indicated, in this case 2 itemsIn JavaScript
myList.pop();
myList.pop(1); //=> "b" Removes and returns the element at index 1In Python
len(my_list)In Ruby
my_list.lengthIn JavaScript
myList.length();In Python
min([1, 2, 3])
max([1, 2, 3])In Ruby
[1, 2, 3].min
[1, 2, 3].maxIn JavaScript
Math.min(...[1, 2, 3]);
Math.max(...[1, 2, 3]);In Python
1 in [1, 2, 3]In Ruby
[1, 2, 3].include?(1)In JavaScript
[1, 2, 3].includes(1);In Python
my_list.sort() # Sorts the list in place, doesn't return anythingIn Ruby
my_list.sort # Sorts
my_list.sort! # Sorts the list in placeIn JavaScript
myList.sort(); // Sorts the list in place, and returns itIn Python
my_list.reverse() # Reverses the list in place, doesn't return anythingIn Ruby
my_list.reverse # Reverses
my_list.reverse! # Reverses the list in placeIn JavaScript
myList.reverse(); // Reverses the list in place, and returns itIn 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
# cIn JavaScript
There's no built-in method to do this.
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.
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.
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);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.
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 };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 listIn 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 arrayIn JavaScript
myObj = {
apples: 2.99,
oranges: 1.99,
watermelon: 0.5,
};
myObj.apple;
Object.keys(myObj);
Object.values(myObj);
Object.entries(myObj);In Python
"a" in {"a": 1}In Ruby
{ a: 1 }.key?(:a)In JavaScript
"a" in { a: 1 };In Python
if True:
print("✅")
elif True:
print("❌")
else:
print("❌")In Ruby
if true
puts('✅')
elsif true
puts('❌')
else
puts('❌')
endIn JavaScript
if (true) {
console.log("✅");
} else if (true) {
console.log("❌");
} else {
console.log("❌");
}In Python
"✅" if True else "❌"In Ruby and JavaScript
true ? "✅" : "❌"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'
endIn 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");
}In Python
for char in ["a", "b", "c"]:
print(char)In Ruby
%w[a b c].each do |char|
puts char
endIn JavaScript
for (char of ["a", "b", "c"]) {
console.log(char);
}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}"
endIn JavaScript
for ([index, char] of ["a", "b", "c"].entries()) {
console.log(`index: ${index}, char: ${char}`);
}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}"
endIn JavaScript
const myObject = { a: 1, b: 2, c: 3 };
for (const k in myObject) {
console.log(`k:${k}, v:${myObject[k]}`);
}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
endIn JavaScript
let n = 0;
while (n < 11) {
console.log(n);
n++;
}Breaks out of the closest enclosing loop. The same break keyword is used in all three languages.
Skips the rest of the current iteration and goes to the top of the closeset enclosing loop.
In Python
continueIn Ruby
nextIn JavaScript
continue;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