DEV Community 👩‍💻👨‍💻

Ravi Katta
Ravi Katta

Posted on • Updated on

Ruby vs Javascript vs Python : Syntax & Semantics

An analogy between the Ruby, Javascript, and Python languages

Table Of Contents

  1. Basics Intro
  2. Arrays Functions
  3. Compound Arrays
  4. String Functions
  5. Numerical Functions
  6. Logical Conditions
  7. Class and Methods or Functions
  8. Regular expression (Regex)
  9. Type Conversion
  10. Heredocs

Basics Intro

Description Ruby Javascript Python
Start Cli irb python node
Integers & floats declaration x = 1 ; y = 0.23 let x = 1; var y = 0.23 x = 1 ; y = 0.23
Contants Declaration W = 'ruby'.freeze const w = 'js' W = 'ruby'
Variables in strings "one is #{x}" one is ${w}\ "one is {}".format(x)
Line Comment # this is comment // this is comment # this is comment
Block comments =being ; =end /* block comment */ ''' block comment '''
write output puts 'write output' console.log('write output')document.write("write HTML") print('write output')
Arrays , Lists arr = [1,'a',true] ; arr = Array.new let arr = [1,'a',true] arr = [1,'a',True]
Hashes, Objects, dictionaries hash = { 'a' => 2, :b => 4 } var obj = { 1 : 2 , 'a' : 4} dict = {1: 2, 'd': 'e' }
Destructuring a,b,c = [2,3,4] ; p b var {x : a , y: b} = {x : 1, y : 2} ; console.log(b) a,b,c = [2,3,4]

Arrays Functions

where x is [3,4,5,6,7,8]

Description Ruby Javascript Python
Remove last element x.pop
x.pop(2)
x.pop() x.pop()
Remove first element x.shift(9) x.shift() x.remove(x[0])
del x[0]
Add last element x.push(9)
x.append(9)
x << 9
x.push(9)
y.concat(5)
x.append(9); x.extend([9]); x.insert(len(x), 9)
Add first element x.unshift(2) x.unshift(2) x.insert(0,2)
Sort x.sort x.sort() x.sort()
Reverse x.reverse x.reverse() x.reverse()
Count x.count(6) var count = {};
y.forEach(val => count[val] = (count[val] \
\
Length x.length; x.size; x.count y.length len(y)
Maximum x.max Math.max(...x) max(x)
Minimum x.min Math.min(...x) min(x)
index x.index(3) x.indexOf(3) x.index(3)
insert x.insert(2, 'Feb') x.splice(1, 0, 'Feb') x.insert(2, 'Feb')
Make a copy y = x.dup let y = [...x] y = x[:]
Select, filter x.select{\ el\ el > 4 }
Reduce x.reduce(:+) lx.reduce((result,el)=> result + el,0) reduce(lambda result,y: result + y, x)
Map x.map{\ el\ el*2}
Each z = [] x.each{\ el\ z << el*2} p z
Reverse loop z = [] x.reverse_each{\ el\ z << el*2} p z
Clear , Reset x.clear x = [] del x[:]

Compound arrays

where, x is [1,2,3] & y is [2,4,5,6]

Description Ruby Javascript Python
Intersection x & y #=> [2] x.filter(e => y.includes(e)) list(set(x) & set(y))
Union x \ yx.union(y) var z = [...x,...y][...new Set( z )] 'or'Array.from(new Set(z))
Join x + y [...x,...y] x + y
Difference x - y x.filter(e => !y.includes(e)); list(set(x) - set(y))

Strings Functions

where, s = 'Cheat sheet '

Description Ruby Javascript Python
UpperCase s.upcase s.toUpperCase() s.upper()
LowerCase s.downcase s.toLowerCase() s.upper()
SwapCase s.swapcase NA s.swapcase()
Trim s.strip! s.trim() s.strip()
StartsWith s.start_with?('cheat') s.startsWith('Cheat') s.startswith('Cheat')
Repeat 'Hi ' * 3 'Hi '.repeat(3) 'Hi ' * 3
Split 'asdf'.split('') 'asdf'.split('') list('asdf') 'a#s#d'.split('#')
Join ['a','s','d','f'].join() ["a", "s", "d", "f"].join('') ''.join(['a','s','d'])
Replace s.replace('Hey')
Find
Count

Numerical Functions

where, el = -22.45

Description Ruby Javascript Python
Ceil el.ceil Math.ceil(el) import math math.ceil(el)
Floor el.floor Math.floor(el) math.floor(el)
Round el.round(1) Math.round(el) round(el)
Absolute el.abs Math.abs(el) abs(el)
Random rand(10) Math.ceil(Math.random(10) * 11) import random random.randrange(1,10)
Zero el.zero?
Negative el.negative?

Logical Conditions

Description Ruby Javascript Python
If if elsif else end if : elif : else: if () {} else if () {} else {}
case case a when else end switch(expression) {case x:break;case y: break; default:} NA
Ternary Operator true == false ? 1 : 2 true == false ? 1 : 2 1 if (True == False) else 2

Class and Methods or Functions

Description Ruby Javascript Python
Instance Methods def name(input) p inputend name = function(input) {return ${input};} name = (input) => "input" def name(input): print("This is " + input)
Static Methods def self.age(input) p inputend static age(input) {return ${input};} @classmethod def age(input): print("This is " + input)
Class class Personattr_accessor :name def initialize(name)@name = nameendend class Person {constructor(name) {this.name = name;}} class Person:def init(self, name):self.name = name
create instance Object p = Person.new('Bezos') let p = new Person("Bezos")let p1 = Object.create(Person) p = Person("Bezos")
Single Inheritance class Employee < Persondef initialize(name)super name@name = nameendend class Employee extends Person {constructor(name) { super(name)this.name = name;}} class Employee(Person):def init(self, name):self.name = name
Multiple Inheritance module Studentdef walkendend class Personinclude Humanend class Student extends Person class Student(Person):
default values def name(input='bezos') end function(input='bezos') def name(input='bezos')

Regular expression (Regex)

where, lx = "titan titan titan"

Description Ruby Javascript Python
First occurrence lx.match(/t[a-z]*n/)[0] (/t[a-z]*n/).test(lx) //=> true import rere.search("t[a-z]*n", lx).group()
All occurrences lx.scan(/t[a-z]*n/) lx.match(/t[a-z]*n/gi) re.findall("t[a-z]*n",lx)

Type Conversion

Description Ruby Javascript Python
string to Integer where, str2int = \'99\' str2int.to_i int(str2int) parseInt(str2int) Number(str2int)
Integer to string where, int2str = 66 int2str.to_s str(int2str) int2str.toString()

Heredocs

Description Ruby Javascript Python
Multiline string content = <<~HEREDOCI welcome your contributions.please suggesta topic or report an issueHEREDOCp content content = """ I welcome your contributions.please suggesta topic or report an issue"""print(content)

Top comments (0)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠