diff --git a/assets/bootstrap/glyphicons-halflings-regular-278e49a8.woff b/assets/bootstrap/glyphicons-halflings-regular-278e49a8.woff new file mode 100644 index 0000000..9e61285 Binary files /dev/null and b/assets/bootstrap/glyphicons-halflings-regular-278e49a8.woff differ diff --git a/assets/bootstrap/glyphicons-halflings-regular-44bc1850.ttf b/assets/bootstrap/glyphicons-halflings-regular-44bc1850.ttf new file mode 100644 index 0000000..1413fc6 Binary files /dev/null and b/assets/bootstrap/glyphicons-halflings-regular-44bc1850.ttf differ diff --git a/assets/bootstrap/glyphicons-halflings-regular-86b6f62b.eot b/assets/bootstrap/glyphicons-halflings-regular-86b6f62b.eot new file mode 100644 index 0000000..b93a495 Binary files /dev/null and b/assets/bootstrap/glyphicons-halflings-regular-86b6f62b.eot differ diff --git a/assets/bootstrap/glyphicons-halflings-regular-ca35b697.woff2 b/assets/bootstrap/glyphicons-halflings-regular-ca35b697.woff2 new file mode 100644 index 0000000..64539b5 Binary files /dev/null and b/assets/bootstrap/glyphicons-halflings-regular-ca35b697.woff2 differ diff --git a/assets/bootstrap/glyphicons-halflings-regular-de51a849.svg b/assets/bootstrap/glyphicons-halflings-regular-de51a849.svg new file mode 100644 index 0000000..94fb549 --- /dev/null +++ b/assets/bootstrap/glyphicons-halflings-regular-de51a849.svg @@ -0,0 +1,288 @@ + + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..58f5a0f --- /dev/null +++ b/index.html @@ -0,0 +1,3965 @@ + + +
+ + +greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
puts 'I like beer'.split
+
+
+I +like +beer ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
puts ' eh? '.strip
+
+
+eh? ++
print(' eh? '.strip())
+
+
+eh? ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
i = 9
+i += 1
+puts i
+
+
+10 ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
puts rand(1..2)
+
+
+1 ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
puts 10.to_f
+
+
+10.0 ++
print(float(10))
+
+
+10.0 ++
puts 10.to_s
+
+
+10 ++
print(str(10))
+
+
+10 ++
puts '5'.to_i
+
+
+5 ++
print(int('5'))
+
+
+5 ++
puts '10'.is_a? String
+
+
+true ++
print(isinstance('10', str))
+
+
+True ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
puts ['first', 1]
+
+
+first +1 ++
print(['first', 1])
+
+
+['first', 1] ++
puts [1, 2].include? 1
+
+
+true ++
print(1 in [1, 2])
+
+
+True ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
puts [1, 2, 3].size
+
+
+3 ++
print(len([1, 2, 3]))
+
+
+3 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
puts %w(a b a).uniq
+
+
+a +b ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
puts 'Hello' if true
+
+
+Hello ++
if True:
+ print('Hello')
+
+
+Hello ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
puts false ? 'no' : 'yes'
+
+
+yes ++
print('no' if False else 'yes')
+
+
+yes ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
puts Math.sqrt(9)
+
+
+3.0 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
# it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
console.log(' eh? '.trim());
+
+
+eh? ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
console.log((10).toFixed(1));
+
+
+10.0 ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
console.log((10).toString());
+
+
+10 ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
console.log(parseInt('5', 10));
+
+
+5 ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
console.log(typeof '10' === 'string');
+
+
+true ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
console.log([1, 2].includes(1));
+
+
+true ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
console.log([1, 2, 3].length);
+
+
+3 ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
if (true) console.log('Hello');
+
+
+Hello ++
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
console.log(false ? 'no' : 'yes');
+
+
+yes ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
console.log(Math.sqrt(9));
+
+
+3 ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+// it's a comment
+
+
+
+// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
<?php
+
+echo trim(" eh? ");
+
+eh?+
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
<?php
+
+echo rand(1, 2);
+
+1+
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
<?php
+
+echo sqrt(9);
+
+
+3+
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+<?php
+
+// it's a comment
+
+
+
+// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
print(' eh? '.strip())
+
+
+eh? ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
print(float(10))
+
+
+10.0 ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
print(str(10))
+
+
+10 ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
print(int('5'))
+
+
+5 ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
print(isinstance('10', str))
+
+
+True ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
print(['first', 1])
+
+
+['first', 1] ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
print(1 in [1, 2])
+
+
+True ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
print(len([1, 2, 3]))
+
+
+3 ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
if True:
+ print('Hello')
+
+
+Hello ++
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
print('no' if False else 'yes')
+
+
+yes ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
puts 'I like beer'.split
+
+
+I +like +beer ++
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
puts ' eh? '.strip
+
+
+eh? ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
i = 9
+i += 1
+puts i
+
+
+10 ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
puts rand(1..2)
+
+
+1 ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
puts 10.to_f
+
+
+10.0 ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
puts 10.to_s
+
+
+10 ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
puts '5'.to_i
+
+
+5 ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
puts '10'.is_a? String
+
+
+true ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
puts ['first', 1]
+
+
+first +1 ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
puts [1, 2].include? 1
+
+
+true ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
puts [1, 2, 3].size
+
+
+3 ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
puts %w(a b a).uniq
+
+
+a +b ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
puts 'Hello' if true
+
+
+Hello ++
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
puts false ? 'no' : 'yes'
+
+
+yes ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
puts Math.sqrt(9)
+
+
+3.0 ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
console.log(' eh? '.trim());
+
+
+eh? ++
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
console.log((10).toFixed(1));
+
+
+10.0 ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
console.log((10).toString());
+
+
+10 ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
console.log(parseInt('5', 10));
+
+
+5 ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
console.log(typeof '10' === 'string');
+
+
+true ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
console.log([1, 2].includes(1));
+
+
+true ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
console.log([1, 2, 3].length);
+
+
+3 ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
if (true) console.log('Hello');
+
+
+Hello ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
console.log(false ? 'no' : 'yes');
+
+
+yes ++
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
console.log(Math.sqrt(9));
+
+
+3 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
// it's a comment
+
+
+
+class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
console.log(' eh? '.trim());
+
+
+eh? ++
console.log(' eh? '.trim());
+
+
+eh? ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
console.log((10).toFixed(1));
+
+
+10.0 ++
console.log((10).toFixed(1));
+
+
+10.0 ++
console.log((10).toString());
+
+
+10 ++
console.log((10).toString());
+
+
+10 ++
console.log(parseInt('5', 10));
+
+
+5 ++
console.log(parseInt('5', 10));
+
+
+5 ++
console.log(typeof '10' === 'string');
+
+
+true ++
console.log(typeof '10' === 'string');
+
+
+true ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
console.log([1, 2].includes(1));
+
+
+true ++
console.log([1, 2].includes(1));
+
+
+true ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
console.log([1, 2, 3].length);
+
+
+3 ++
console.log([1, 2, 3].length);
+
+
+3 ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
if (true) console.log('Hello');
+
+
+Hello ++
if (true) console.log('Hello');
+
+
+Hello ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
console.log(false ? 'no' : 'yes');
+
+
+yes ++
console.log(false ? 'no' : 'yes');
+
+
+yes ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
console.log(Math.sqrt(9));
+
+
+3 ++
console.log(Math.sqrt(9));
+
+
+3 ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
// it's a comment
+
+
+
+// it's a comment
+
+
+
+// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
console.log(' eh? '.trim());
+
+
+eh? ++
<?php
+
+echo trim(" eh? ");
+
+eh?+
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
<?php
+
+echo rand(1, 2);
+
+1+
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
console.log((10).toFixed(1));
+
+
+10.0 ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
console.log((10).toString());
+
+
+10 ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
console.log(parseInt('5', 10));
+
+
+5 ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
console.log(typeof '10' === 'string');
+
+
+true ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
console.log([1, 2].includes(1));
+
+
+true ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
console.log([1, 2, 3].length);
+
+
+3 ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
if (true) console.log('Hello');
+
+
+Hello ++
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
console.log(false ? 'no' : 'yes');
+
+
+yes ++
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
console.log(Math.sqrt(9));
+
+
+3 ++
<?php
+
+echo sqrt(9);
+
+
+3+
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
// it's a comment
+
+
+
+<?php
+
+// it's a comment
+
+
+
+// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
console.log(' eh? '.trim());
+
+
+eh? ++
print(' eh? '.strip())
+
+
+eh? ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
console.log((10).toFixed(1));
+
+
+10.0 ++
print(float(10))
+
+
+10.0 ++
console.log((10).toString());
+
+
+10 ++
print(str(10))
+
+
+10 ++
console.log(parseInt('5', 10));
+
+
+5 ++
print(int('5'))
+
+
+5 ++
console.log(typeof '10' === 'string');
+
+
+true ++
print(isinstance('10', str))
+
+
+True ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
print(['first', 1])
+
+
+['first', 1] ++
console.log([1, 2].includes(1));
+
+
+true ++
print(1 in [1, 2])
+
+
+True ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
console.log([1, 2, 3].length);
+
+
+3 ++
print(len([1, 2, 3]))
+
+
+3 ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
if (true) console.log('Hello');
+
+
+Hello ++
if True:
+ print('Hello')
+
+
+Hello ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
console.log(false ? 'no' : 'yes');
+
+
+yes ++
print('no' if False else 'yes')
+
+
+yes ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
console.log(Math.sqrt(9));
+
+
+3 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
// it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
puts 'I like beer'.split
+
+
+I +like +beer ++
console.log(' eh? '.trim());
+
+
+eh? ++
puts ' eh? '.strip
+
+
+eh? ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
i = 9
+i += 1
+puts i
+
+
+10 ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
puts rand(1..2)
+
+
+1 ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
console.log((10).toFixed(1));
+
+
+10.0 ++
puts 10.to_f
+
+
+10.0 ++
console.log((10).toString());
+
+
+10 ++
puts 10.to_s
+
+
+10 ++
console.log(parseInt('5', 10));
+
+
+5 ++
puts '5'.to_i
+
+
+5 ++
console.log(typeof '10' === 'string');
+
+
+true ++
puts '10'.is_a? String
+
+
+true ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
puts ['first', 1]
+
+
+first +1 ++
console.log([1, 2].includes(1));
+
+
+true ++
puts [1, 2].include? 1
+
+
+true ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
console.log([1, 2, 3].length);
+
+
+3 ++
puts [1, 2, 3].size
+
+
+3 ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
puts %w(a b a).uniq
+
+
+a +b ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
if (true) console.log('Hello');
+
+
+Hello ++
puts 'Hello' if true
+
+
+Hello ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
console.log(false ? 'no' : 'yes');
+
+
+yes ++
puts false ? 'no' : 'yes'
+
+
+yes ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
console.log(Math.sqrt(9));
+
+
+3 ++
puts Math.sqrt(9)
+
+
+3.0 ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
// it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
t |
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
<?php
+
+echo trim(" eh? ");
+
+eh?+
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
<?php
+
+echo rand(1, 2);
+
+1+
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
<?php
+
+echo sqrt(9);
+
+
+3+
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
<?php
+
+// it's a comment
+
+
+
+class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
<?php
+
+echo trim(" eh? ");
+
+eh?+
console.log(' eh? '.trim());
+
+
+eh? ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
<?php
+
+echo rand(1, 2);
+
+1+
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
console.log((10).toFixed(1));
+
+
+10.0 ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
console.log((10).toString());
+
+
+10 ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
console.log(parseInt('5', 10));
+
+
+5 ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
console.log(typeof '10' === 'string');
+
+
+true ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
console.log([1, 2].includes(1));
+
+
+true ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
console.log([1, 2, 3].length);
+
+
+3 ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
if (true) console.log('Hello');
+
+
+Hello ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
console.log(false ? 'no' : 'yes');
+
+
+yes ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
<?php
+
+echo sqrt(9);
+
+
+3+
console.log(Math.sqrt(9));
+
+
+3 ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
<?php
+
+// it's a comment
+
+
+
+// it's a comment
+
+
+
+<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
<?php
+
+echo trim(" eh? ");
+
+eh?+
<?php
+
+echo trim(" eh? ");
+
+eh?+
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
<?php
+
+echo rand(1, 2);
+
+1+
<?php
+
+echo rand(1, 2);
+
+1+
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
<?php
+
+echo sqrt(9);
+
+
+3+
<?php
+
+echo sqrt(9);
+
+
+3+
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
<?php
+
+// it's a comment
+
+
+
+<?php
+
+// it's a comment
+
+
+
+<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
<?php
+
+echo trim(" eh? ");
+
+eh?+
print(' eh? '.strip())
+
+
+eh? ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
i = 9
+i += 1
+print(i)
+
+
+10 ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
<?php
+
+echo rand(1, 2);
+
+1+
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
print(float(10))
+
+
+10.0 ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
print(str(10))
+
+
+10 ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
print(int('5'))
+
+
+5 ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
print(isinstance('10', str))
+
+
+True ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
print(['first', 1])
+
+
+['first', 1] ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
print(1 in [1, 2])
+
+
+True ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
print(len([1, 2, 3]))
+
+
+3 ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
if True:
+ print('Hello')
+
+
+Hello ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
print('no' if False else 'yes')
+
+
+yes ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
<?php
+
+echo sqrt(9);
+
+
+3+
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
<?php
+
+// it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
puts 'I like beer'.split
+
+
+I +like +beer ++
<?php
+
+echo trim(" eh? ");
+
+eh?+
puts ' eh? '.strip
+
+
+eh? ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
i = 9
+i += 1
+puts i
+
+
+10 ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
<?php
+
+echo rand(1, 2);
+
+1+
puts rand(1..2)
+
+
+1 ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
puts 10.to_f
+
+
+10.0 ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
puts 10.to_s
+
+
+10 ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
puts '5'.to_i
+
+
+5 ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
puts '10'.is_a? String
+
+
+true ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
puts ['first', 1]
+
+
+first +1 ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
puts [1, 2].include? 1
+
+
+true ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
puts [1, 2, 3].size
+
+
+3 ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
puts %w(a b a).uniq
+
+
+a +b ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
puts 'Hello' if true
+
+
+Hello ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
puts false ? 'no' : 'yes'
+
+
+yes ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
<?php
+
+echo sqrt(9);
+
+
+3+
puts Math.sqrt(9)
+
+
+3.0 ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
<?php
+
+// it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
print(' eh? '.strip())
+
+
+eh? ++
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
print(float(10))
+
+
+10.0 ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
print(str(10))
+
+
+10 ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
print(int('5'))
+
+
+5 ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
print(isinstance('10', str))
+
+
+True ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
print(['first', 1])
+
+
+['first', 1] ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
print(1 in [1, 2])
+
+
+True ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
print(len([1, 2, 3]))
+
+
+3 ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
if True:
+ print('Hello')
+
+
+Hello ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
print('no' if False else 'yes')
+
+
+yes ++
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
# it's a comment
+
+
+
+class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
print(' eh? '.strip())
+
+
+eh? ++
console.log(' eh? '.trim());
+
+
+eh? ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
print(float(10))
+
+
+10.0 ++
console.log((10).toFixed(1));
+
+
+10.0 ++
print(str(10))
+
+
+10 ++
console.log((10).toString());
+
+
+10 ++
print(int('5'))
+
+
+5 ++
console.log(parseInt('5', 10));
+
+
+5 ++
print(isinstance('10', str))
+
+
+True ++
console.log(typeof '10' === 'string');
+
+
+true ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
print(['first', 1])
+
+
+['first', 1] ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
print(1 in [1, 2])
+
+
+True ++
console.log([1, 2].includes(1));
+
+
+true ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
print(len([1, 2, 3]))
+
+
+3 ++
console.log([1, 2, 3].length);
+
+
+3 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
if True:
+ print('Hello')
+
+
+Hello ++
if (true) console.log('Hello');
+
+
+Hello ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
print('no' if False else 'yes')
+
+
+yes ++
console.log(false ? 'no' : 'yes');
+
+
+yes ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
console.log(Math.sqrt(9));
+
+
+3 ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
# it's a comment
+
+
+
+// it's a comment
+
+
+
+speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
print(' eh? '.strip())
+
+
+eh? ++
<?php
+
+echo trim(" eh? ");
+
+eh?+
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
<?php
+
+echo rand(1, 2);
+
+1+
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
print(float(10))
+
+
+10.0 ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
print(str(10))
+
+
+10 ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
print(int('5'))
+
+
+5 ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
print(isinstance('10', str))
+
+
+True ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
print(['first', 1])
+
+
+['first', 1] ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
print(1 in [1, 2])
+
+
+True ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
print(len([1, 2, 3]))
+
+
+3 ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
if True:
+ print('Hello')
+
+
+Hello ++
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
print('no' if False else 'yes')
+
+
+yes ++
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
<?php
+
+echo sqrt(9);
+
+
+3+
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
# it's a comment
+
+
+
+<?php
+
+// it's a comment
+
+
+
+speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
print(' eh? '.strip())
+
+
+eh? ++
print(' eh? '.strip())
+
+
+eh? ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
print(float(10))
+
+
+10.0 ++
print(float(10))
+
+
+10.0 ++
print(str(10))
+
+
+10 ++
print(str(10))
+
+
+10 ++
print(int('5'))
+
+
+5 ++
print(int('5'))
+
+
+5 ++
print(isinstance('10', str))
+
+
+True ++
print(isinstance('10', str))
+
+
+True ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
print(['first', 1])
+
+
+['first', 1] ++
print(['first', 1])
+
+
+['first', 1] ++
print(1 in [1, 2])
+
+
+True ++
print(1 in [1, 2])
+
+
+True ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
print(len([1, 2, 3]))
+
+
+3 ++
print(len([1, 2, 3]))
+
+
+3 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
if True:
+ print('Hello')
+
+
+Hello ++
if True:
+ print('Hello')
+
+
+Hello ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
print('no' if False else 'yes')
+
+
+yes ++
print('no' if False else 'yes')
+
+
+yes ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
# it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
puts 'I like beer'.split
+
+
+I +like +beer ++
print(' eh? '.strip())
+
+
+eh? ++
puts ' eh? '.strip
+
+
+eh? ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
i = 9
+i += 1
+puts i
+
+
+10 ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
puts rand(1..2)
+
+
+1 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
print(float(10))
+
+
+10.0 ++
puts 10.to_f
+
+
+10.0 ++
print(str(10))
+
+
+10 ++
puts 10.to_s
+
+
+10 ++
print(int('5'))
+
+
+5 ++
puts '5'.to_i
+
+
+5 ++
print(isinstance('10', str))
+
+
+True ++
puts '10'.is_a? String
+
+
+true ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
print(['first', 1])
+
+
+['first', 1] ++
puts ['first', 1]
+
+
+first +1 ++
print(1 in [1, 2])
+
+
+True ++
puts [1, 2].include? 1
+
+
+true ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
print(len([1, 2, 3]))
+
+
+3 ++
puts [1, 2, 3].size
+
+
+3 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
puts %w(a b a).uniq
+
+
+a +b ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
if True:
+ print('Hello')
+
+
+Hello ++
puts 'Hello' if true
+
+
+Hello ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
print('no' if False else 'yes')
+
+
+yes ++
puts false ? 'no' : 'yes'
+
+
+yes ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
puts Math.sqrt(9)
+
+
+3.0 ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
# it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
class StringCreate {
+ public static void main(String[] args) {
+ String greeting = "Hello World!";
+ System.out.println(greeting);
+ }
+}
+
+
+Hello World! ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
class StringConcat {
+ public static void main(String[] args) {
+ System.out.println("Don't worry," + " be happy");
+ }
+}
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
class StringRemove {
+ public static void main(String[] args) {
+ String s = "This is not funny! I am not like him!";
+ System.out.println(s.replaceAll("not ", ""));
+ }
+}
+
+
+This is funny! I am like him! ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
class StringReplace {
+ public static void main(String[] args) {
+ String s = "You should work";
+ System.out.println(s.replaceAll("work", "rest"));
+ }
+}
+
+
+You should rest ++
puts 'I like beer'.split
+
+
+I +like +beer ++
import java.util.Arrays;
+
+class StringSplit {
+ public static void main(String[] args) {
+ String s = "I like beer";
+ String[] arr = s.split(" ");
+ System.out.println(Arrays.toString(arr));
+ }
+}
+
+
+[I, like, beer] ++
puts ' eh? '.strip
+
+
+eh? ++
class StringRemoveWhitespace {
+ public static void main(String[] args) {
+ System.out.println(" eh? ".trim());
+ }
+}
+
+
+eh? ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
class StringCompare {
+ public static void main(String[] args) {
+ System.out.println("string".equals("string"));
+ System.out.println(!"string".equals("string"));
+ }
+}
+
+
+true +false ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
import java.util.regex.*;
+
+class StringRegex {
+ public static void main(String[] args) {
+ System.out.println(Pattern.compile("^b").matcher("apple").find());
+ System.out.println(Pattern.compile("^a").matcher("apple").find());
+ }
+}
+
+
+false +true ++
i = 9
+i += 1
+puts i
+
+
+10 ++
class NumberIncrement {
+ public static void main(String[] args) {
+ int i = 9;
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+10 ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
class NumberCompare {
+ public static void main(String[] args) {
+ System.out.println(1 < 2 && 2 < 3);
+ System.out.println(5 == 5);
+ System.out.println(5 != 5);
+ }
+}
+
+
+true +true +false ++
puts rand(1..2)
+
+
+1 ++
import java.util.concurrent.ThreadLocalRandom;
+
+class NumberRandom {
+ public static void main(String[] args) {
+ System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
+ }
+}
+
+
+1 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
class NumberFloat {
+ public static void main(String[] args) {
+ System.out.println(9 / 2);
+ System.out.println(9 / 2.0);
+ System.out.println(Math.floor(9 / 2.0));
+ System.out.println(Math.round(9 / 2.0));
+ }
+}
+
+
+4 +4.5 +4.0 +5 ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
class TypeGetType {
+ public static void main(String[] args) {
+ System.out.println("hi".getClass());
+ System.out.println(new Integer(1).getClass());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal + System.out.println(new Integer(1).getClass()); + ^ +1 warning ++
puts 10.to_f
+
+
+10.0 ++
class TypeIntToFloat {
+ public static void main(String[] args) {
+ System.out.println((float) 10);
+ }
+}
+
+
+10.0 ++
puts 10.to_s
+
+
+10 ++
class TypeIntToString {
+ public static void main(String[] args) {
+ System.out.println(Integer.toString(10));
+ }
+}
+
+
+10 ++
puts '5'.to_i
+
+
+5 ++
class TypeStringToInt {
+ public static void main(String[] args) {
+ System.out.println(Integer.parseInt("10"));
+ }
+}
+
+
+10 ++
puts '10'.is_a? String
+
+
+true ++
class TypeIsString {
+ public static void main(String[] args) {
+ System.out.println("10" instanceof String);
+ }
+}
+
+
+true ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
import java.util.*;
+
+class TypeNullTrueFalse {
+ public static void main(String[] args) {
+ List<String> emptyArray = new ArrayList<String>();
+ System.out.println(emptyArray.isEmpty());
+
+ String emptyString = "";
+ System.out.println(emptyString.isEmpty());
+
+ String nullVar = null;
+ System.out.println(nullVar == null);
+ }
+}
+
+
+true +true +true ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
import java.util.*;
+
+class ArrayCreatePopulated {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("first", "second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
import java.util.*;
+
+class ArrayAdd {
+ public static void main(String[] args) {
+ List<String> arr = new ArrayList<String>();
+ arr.add("first");
+ arr.add("second");
+ System.out.println(arr);
+ }
+}
+
+
+[first, second] ++
puts ['first', 1]
+
+
+first +1 ++
import java.util.*;
+
+class ArrayDifferentTypes {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList("first", 1));
+ }
+}
+
+
+[first, 1] ++
puts [1, 2].include? 1
+
+
+true ++
import java.util.*;
+
+class ArrayIsInclude {
+ public static void main(String[] args) {
+ System.out.println(Arrays.asList(1, 2).contains(1));
+ }
+}
+
+
+true ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
import java.util.*;
+
+class ArrayIterate {
+ public static void main(String[] args) {
+ for (int num : Arrays.asList(1, 2)) {
+ System.out.println(num);
+ }
+ }
+}
+
+
+1 +2 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
import java.util.*;
+
+class ArrayIterateWithIndex {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ for (int i = 0; i < arr.size(); i++) {
+ System.out.println(arr.get(i));
+ System.out.println(i);
+ }
+ }
+}
+
+
+one +0 +two +1 ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
import java.util.*;
+
+class ArrayGetFirstAndLast {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("one", "two");
+ System.out.println(arr.get(0));
+ System.out.println(arr.get(arr.size() - 1));
+ }
+}
+
+
+one +two ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
import java.util.*;
+
+class ArrayFind {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ int first = 0;
+ for (int n : arr) {
+ if (n % 2 == 0) {
+ first = n;
+ break;
+ }
+ }
+ System.out.println(first);
+ }
+}
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
import java.util.*;
+
+class ArraySelect {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> all = new ArrayList<Integer>();
+ for (int n : arr)
+ if (n % 2 == 0)
+ all.add(n);
+ System.out.println(all);
+ }
+}
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
import java.util.*;
+
+class ArrayMap {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 5, 10, 20);
+ List<Integer> mapped = new ArrayList<Integer>();
+ for (int n : arr)
+ mapped.add(n * 2);
+ System.out.println(mapped);
+ }
+}
+
+
+[2, 10, 20, 40] ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
import java.util.*;
+
+class ArrayConcat {
+ public static void main(String[] args) {
+ List<Integer> arr1 = Arrays.asList(1, 2);
+ List<Integer> arr2 = Arrays.asList(3, 4);
+ List<Integer> concated = new ArrayList<Integer>(arr1);
+ concated.addAll(arr2);
+ System.out.println(concated);
+ }
+}
+
+
+[1, 2, 3, 4] ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
import java.util.*;
+
+class ArraySort {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(4, 2, 3, 1);
+ Collections.sort(arr);
+ System.out.println(arr);
+ }
+}
+
+
+[1, 2, 3, 4] ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
import java.util.*;
+
+class ArrayMulti {
+ public static void main(String[] args) {
+ List<List<String>> arr = new ArrayList<List<String>>();
+ arr.add(Arrays.asList("first", "second"));
+ arr.add(Arrays.asList("third", "forth"));
+ System.out.println(arr.get(1).get(1));
+ }
+}
+
+
+forth ++
puts [1, 2, 3].size
+
+
+3 ++
import java.util.*;
+
+class ArraySize {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(arr.size());
+ }
+}
+
+
+3 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
import java.util.*;
+
+class ArrayCount {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 11, 111);
+ int count = 0;
+ for (int n : arr)
+ if (n > 10)
+ count++;
+ System.out.println(count);
+ }
+}
+
+
+2 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
import java.util.*;
+
+class ArrayReduce {
+ public static void main(String[] args) {
+ int sum = 0;
+ for (int n : Arrays.asList(1, 2, 3))
+ sum += n;
+ System.out.println(sum);
+ }
+}
+
+
+6 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
import java.util.*;
+
+class ArrayIndexOfElement {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "c");
+ System.out.println(arr.indexOf("c"));
+ }
+}
+
+
+2 ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
import java.util.*;
+
+class ArrayDeleteElement {
+ public static void main(String[] args) {
+ List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
+ Iterator<String> iter = arr.iterator();
+ while(iter.hasNext()) {
+ if(iter.next().equalsIgnoreCase("b"))
+ iter.remove();
+ }
+ System.out.println(arr);
+ }
+}
+
+
+[a, c] ++
puts %w(a b a).uniq
+
+
+a +b ++
import java.util.*;
+
+class ArrayUnique {
+ public static void main(String[] args) {
+ List<String> arr = Arrays.asList("a", "b", "a");
+ Set<String> unique = new LinkedHashSet<>(arr);
+ System.out.println(unique);
+ }
+}
+
+
+[a, b] ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
import java.util.*;
+
+class HashCreatePopulated {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
import java.util.*;
+
+class HashAdd {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>();
+ options.put("fontSize", "10");
+ options.put("fontFamily", "Arial");
+ System.out.println(options);
+ }
+}
+
+
+{fontFamily=Arial, fontSize=10} ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
import java.util.*;
+
+class HashIterate {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ for (Map.Entry<String, String> entry : options.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue());
+ }
+ }
+}
+
+
+fontFamily +Arial +fontSize +10 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
import java.util.*;
+
+class HashIsInclude {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.containsKey("fontSize"));
+ }
+}
+
+
+true ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
import java.util.*;
+
+class HashGetValue {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.get("fonSize"));
+ }
+}
+
+
+null ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
import java.util.*;
+
+class HashSize {
+ public static void main(String[] args) {
+ Map<String, String> options = new HashMap<String, String>() {{
+ put("fontSize", "10");
+ put("fontFamily", "Arial");
+ }};
+ System.out.println(options.size());
+ }
+}
+
+
+2 ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
class OtherStructureBoolean {
+ public static void main(String[] args) {
+ boolean tryIt = true;
+ if (tryIt)
+ System.out.println("Garlic gum is not funny");
+ }
+}
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
class OtherStructureConstant {
+ public static void main(String[] args) {
+ final int COST = 100;
+ COST = 50;
+ System.out.println(COST);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST + COST = 50; + ^ +1 error ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
enum Color {
+ RED("#FF0000"),
+ GREEN("#00FF00");
+
+ private String color;
+
+ private Color(String color) {
+ this.color = color;
+ }
+
+ public String toString() {
+ return color;
+ }
+}
+
+class OtherStructureConstantList {
+ public static void main(String[] args) {
+ System.out.println(Color.GREEN);
+ }
+}
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
puts 'Hello' if true
+
+
+Hello ++
class ConditionalIf {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("Hello");
+ }
+}
+
+
+Hello ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
class ConditionalUnless {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
class ConditionalIfElse {
+ public static void main(String[] args) {
+ if (true)
+ System.out.println("work");
+ else
+ System.out.println("sleep");
+ }
+}
+
+
+work ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
class ConditionalAndOr {
+ public static void main(String[] args) {
+ if (true && false)
+ System.out.println("no");
+ if (true || false)
+ System.out.println("yes");
+ }
+}
+
+
+yes ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
class ConditionalSwitch {
+ public static void main(String[] args) {
+ String s = "Hello!";
+ switch (s) {
+ case "Bye!":
+ System.out.println("wrong");
+ break;
+ case "Hello!":
+ System.out.println("right");
+ break;
+ default: break;
+ }
+ }
+}
+
+
+right ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
puts false ? 'no' : 'yes'
+
+
+yes ++
class ConditionalTernary {
+ public static void main(String[] args) {
+ String s = false ? "no" : "yes";
+ System.out.println(s);
+ }
+}
+
+
+yes ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
class LoopFor {
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; i++)
+ System.out.println(i + ". Hi");
+ }
+}
+
+
+1. Hi +2. Hi +3. Hi ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
class LoopForWithStep {
+ public static void main(String[] args) {
+ for (int i = 0; i <= 4; i += 2)
+ System.out.println(i);
+ }
+}
+
+
+0 +2 +4 ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
class LoopTimes {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++)
+ System.out.println("Hi");
+ }
+}
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
class LoopWhile {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i < 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
class LoopUntil {
+ public static void main(String[] args) {
+ int i = 0;
+ while (i != 3)
+ i++;
+ System.out.println(i);
+ }
+}
+
+
+3 ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
class LoopBreak {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ System.out.println((i + 1) + ". Hi");
+ if (i == 1)
+ break;
+ }
+ }
+}
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
class LoopNext {
+ public static void main(String[] args) {
+ for (int i = 0; i < 3; i++) {
+ if (i == 1)
+ continue;
+ System.out.println((i + 1) + ". Hi");
+ }
+ }
+}
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
import java.util.*;
+
+class MathMaxMin {
+ public static void main(String[] args) {
+ List<Integer> arr = Arrays.asList(1, 2, 3);
+ System.out.println(Collections.min(arr));
+ System.out.println(Collections.max(arr));
+ }
+}
+
+
+1 +3 ++
puts Math.sqrt(9)
+
+
+3.0 ++
class MathSqrt {
+ public static void main(String[] args) {
+ System.out.println(Math.sqrt(9));
+ }
+}
+
+
+3.0 ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
class ErrorTryCatch {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println("Can't divide");
+ } finally {
+ System.out.println("But that's ok");
+ }
+ }
+}
+
+
+Can't divide +But that's ok ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
class ErrorWithAMessage {
+ public static void main(String[] args) {
+ try {
+ int i = 1 / 0;
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+/ by zero ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
class ErrorThrow {
+ public static void main(String[] args) {
+ try {
+ throw new Exception("An error!");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+}
+
+
+An error! ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
import java.io.*;
+
+class FileRead {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/file.txt";
+ String content;
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ content = sb.toString();
+ }
+ System.out.println(content);
+ }
+}
+
+
+Hello +World + ++
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+import java.io.*;
+
+class FileWrite {
+ public static void main(String[] args) throws IOException {
+ String filePath = System.getProperty("user.dir") + "/code/output.txt";
+ try (Writer writer = new BufferedWriter(new OutputStreamWriter(
+ new FileOutputStream(filePath), "utf-8"))) {
+ writer.write("Some glorious content");
+ }
+ }
+}
+
+
+
+puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
class FileGetWorkingDir {
+ public static void main(String[] args) {
+ System.out.println(System.getProperty("user.dir"));
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
import java.net.*;
+
+class FilePath {
+ public static void main(String[] args) {
+ URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile() + "FilePath.class");
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/FilePath.class ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
import java.net.*;
+
+class FileDirPath {
+ public static void main(String[] args) {
+ URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ System.out.println(location.getFile());
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java/ ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
import java.net.*;
+import java.io.*;
+
+class FileParentDirPath {
+ public static void main(String[] args) {
+ URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile()).getParent();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
import java.net.*;
+import java.io.*;
+
+class FileSisterDirPath {
+ public static void main(String[] args) throws IOException {
+ URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
+ String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
+ System.out.println(parentPath);
+ }
+}
+
+
+/Users/evmorov/projects/lang-compare/code/java ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
class MethodDeclare {
+ public static void main(String[] args) {
+ new MethodDeclare().hey();
+ }
+
+ public void hey() {
+ System.out.println("How are you?");
+ }
+}
+
+
+How are you? ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
import java.util.*;
+
+class MethodMultiArg {
+ public static void main(String[] args) {
+ new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
+ }
+
+ public void sweets(boolean buy, String... brands) {
+ if (buy)
+ System.out.println(Arrays.toString(brands));
+ }
+}
+
+
+[snickers, twix, bounty] ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
class MethodReturn {
+ public static void main(String[] args) {
+ MethodReturn obj = new MethodReturn();
+ System.out.println(obj.divide(0, 10));
+ System.out.println(obj.divide(10, 5));
+ }
+
+ public int divide(int a, int b) {
+ if (a == 0)
+ return 0;
+ return a / b;
+ }
+}
+
+
+0 +2 ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassDeclare {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public void walk() {
+ System.out.println("My name is " + this.name + " and I'm walking");
+ }
+}
+
+class ClassConstructor {
+ public static void main(String[] args) {
+ new Animal("Kelya").walk();
+ }
+}
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ public void walk() {
+ bark();
+ guard();
+ System.out.println("I'm walking");
+ }
+
+ public void bark() {
+ System.out.println("Wuf!");
+ }
+
+ private void guard() {
+ System.out.println("WUUUF!");
+ }
+}
+
+class ClassMethodCall {
+ public static void main(String[] args) {
+ new Animal().walk();
+ }
+}
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal {
+ public static void feed() {
+ System.out.println("Om nom nom");
+ }
+}
+
+class ClassClassMethod {
+ public static void main(String[] args) {
+ Animal.feed();
+ }
+}
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal {
+ public void eat(String food) {
+ if (isMeat(food))
+ System.out.println("Om nom nom");
+ }
+
+ private boolean isMeat(String food) {
+ return food.equals("meat");
+ }
+}
+
+class ClassPrivateMethod {
+ public static void main(String[] args) {
+ new Animal().eat("meat");
+ }
+}
+
+
+Om nom nom ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal {
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ greet();
+ }
+
+ private void greet() {
+ System.out.println("Hello! My name is " + this.name);
+ }
+}
+
+class ClassPrivateMethodAccessInstance {
+ public static void main(String[] args) {
+ new Animal("Kelya");
+ }
+}
+
+
+Hello! My name is Kelya ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal {
+ private String toy;
+
+ public void take(String toy) {
+ this.toy = toy;
+ }
+
+ public void play() {
+ System.out.println("I'm playing with " + this.toy);
+ }
+}
+
+class ClassField {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.take("a ball");
+ animal.play();
+ }
+}
+
+
+I'm playing with a ball ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal {
+ private String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+}
+
+class ClassGetSet {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ animal.setName("Kelya");
+ System.out.println(animal.getName());
+ }
+}
+
+
+Kelya ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ public void sing() {
+ System.out.println("Bark!");
+ }
+}
+
+class ClassInheritance {
+ public static void main(String[] args) {
+ new Dog().walk();
+ }
+}
+
+
+I'm walking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
import java.lang.reflect.*;
+
+class Animal {
+ public void walk() {
+ System.out.println("I'm walking");
+ }
+}
+
+class ClassHasMethod {
+ public static void main(String[] args) {
+ Animal animal = new Animal();
+ boolean hasMethod = false;
+ for (Method m : animal.getClass().getMethods()) {
+ if (m.getName().equals("walk")) {
+ hasMethod = true;
+ break;
+ }
+ }
+ System.out.println(hasMethod);
+ }
+}
+
+
+true ++
# it's a comment
+
+
+
+class OtherComment {
+ public static void main(String[] args) {
+ // it's a comment
+ }
+}
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
// OtherFileToImport.java
+// class OtherFileToImport {
+// public OtherFileToImport() {
+// System.out.println("I am imported!");
+// }
+// }
+
+class OtherImportFile {
+ public static void main(String[] args) {
+ new OtherFileToImport();
+ }
+}
+
+
+I am imported! ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherDate {
+ public static void main(String[] args) {
+ String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+ System.out.println(date);
+ }
+}
+
+
+2024-05-28 ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
import java.util.Date;
+import java.text.SimpleDateFormat;
+
+class OtherTime {
+ public static void main(String[] args) {
+ String time = new SimpleDateFormat().format(new Date());
+ System.out.println(time);
+ }
+}
+
+
+28/05/2024, 20:16 ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
class OtherNot {
+ public static void main(String[] args) {
+ boolean angry = false;
+ if (!angry)
+ System.out.println("smile!");
+ }
+}
+
+
+smile! ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
import java.io.*;
+
+class OtherRunCommand {
+ public static void main(String[] args) throws IOException, InterruptedException {
+ String result = "";
+ ProcessBuilder ps = new ProcessBuilder("java", "-version");
+ ps.redirectErrorStream(true);
+ Process pr = ps.start();
+ BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null)
+ result += line + "\n";
+ pr.waitFor();
+ in.close();
+ System.out.println(result);
+ }
+}
+
+
+openjdk version "17.0.8.1" 2023-08-24 +OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1) +OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing) + ++
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
const greeting = 'Hello World!';
+console.log(greeting);
+
+
+Hello World! ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
console.log("Don't worry" + ' be happy');
+
+
+Don't worry be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
const first = "Don't worry,";
+const second = 'be happy';
+console.log(`${first} ${second}`);
+
+
+Don't worry, be happy ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
console.log('This is not funny! I am not like him!'.replace(/not /g, ''));
+
+
+This is funny! I am like him! ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
console.log('You should work'.replace(/work/g, 'rest'));
+
+
+You should rest ++
puts 'I like beer'.split
+
+
+I +like +beer ++
console.log('I like beer'.split(' '));
+
+
+[ 'I', 'like', 'beer' ] ++
puts ' eh? '.strip
+
+
+eh? ++
console.log(' eh? '.trim());
+
+
+eh? ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
console.log('string' === 'string');
+console.log('string' !== 'string');
+
+
+true +false ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
console.log('apple'.match(/^b/));
+console.log('apple'.match(/^a/));
+
+
+null +[ 'a', index: 0, input: 'apple', groups: undefined ] ++
i = 9
+i += 1
+puts i
+
+
+10 ++
let i = 9;
+i++;
+console.log(i);
+
+
+10 ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
console.log(1 < 2 && 2 < 3);
+console.log(5 === 5);
+console.log(5 !== 5);
+
+
+true +true +false ++
puts rand(1..2)
+
+
+1 ++
const min = 1;
+const max = 2;
+console.log(Math.floor(Math.random() * (max - min + 1)) + min);
+
+
+2 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
console.log(9 / 2);
+console.log(9 / 2.0);
+console.log(Math.floor(9 / 2.0));
+console.log(Math.round(9 / 2.0));
+
+
+4.5 +4.5 +4 +5 ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
console.log(typeof 'hi');
+console.log(typeof 1);
+console.log('hi'.constructor.name);
+console.log((1).constructor.name);
+
+
+string +number +String +Number ++
puts 10.to_f
+
+
+10.0 ++
console.log((10).toFixed(1));
+
+
+10.0 ++
puts 10.to_s
+
+
+10 ++
console.log((10).toString());
+
+
+10 ++
puts '5'.to_i
+
+
+5 ++
console.log(parseInt('5', 10));
+
+
+5 ++
puts '10'.is_a? String
+
+
+true ++
console.log(typeof '10' === 'string');
+
+
+true ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
const arr = ['first', 'second'];
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
const arr = [];
+arr.push('first');
+arr.push('second');
+console.log(arr);
+
+
+[ 'first', 'second' ] ++
puts ['first', 1]
+
+
+first +1 ++
console.log(['first', 1]);
+
+
+[ 'first', 1 ] ++
puts [1, 2].include? 1
+
+
+true ++
console.log([1, 2].includes(1));
+
+
+true ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
[1, 2].forEach(num => console.log(num));
+
+
+1 +2 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
['one', 'two'].forEach((num, i) => {
+ console.log(num);
+ console.log(i);
+});
+
+
+one +0 +two +1 ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
const arr = ['one', 'two'];
+const first = arr[0];
+const last = arr[arr.length - 1];
+console.log(first);
+console.log(last);
+
+
+one +two ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
const arr = [1, 5, 10, 20];
+console.log(arr.find(i => i % 2 === 0));
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
const arr = [1, 5, 10, 20];
+console.log(arr.filter(i => i % 2 === 0));
+
+
+[ 10, 20 ] ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
const arr = [1, 5, 10, 20];
+console.log(arr.map(num => num * 2));
+
+
+[ 2, 10, 20, 40 ] ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
console.log([1, 2].concat([3, 4]));
+
+
+[ 1, 2, 3, 4 ] ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
console.log([4, 2, 3, 1].sort());
+
+
+[ 1, 2, 3, 4 ] ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
const multi = [['first', 'second'], ['third', 'forth']];
+console.log(multi[1][1]);
+
+
+forth ++
puts [1, 2, 3].size
+
+
+3 ++
console.log([1, 2, 3].length);
+
+
+3 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
const arr = [1, 11, 111];
+console.log(arr.filter(i => i > 10).length);
+
+
+2 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
console.log([1, 2, 3].reduce((x, y) => x + y));
+
+
+6 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
console.log(['a', 'b', 'c'].indexOf('c'));
+
+
+2 ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
const arr = ['a', 'b', 'c'];
+const newArr = (arr.filter(e => e !== 'b'));
+console.log(newArr);
+
+
+[ 'a', 'c' ] ++
puts %w(a b a).uniq
+
+
+a +b ++
const arr = ['a', 'b', 'a'];
+const unique = arr.filter((value, index, self) => self.indexOf(value) === index);
+console.log(unique);
+
+
+[ 'a', 'b' ] ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
const options = {};
+options.font_size = 10;
+options.font_family = 'Arial';
+console.log(options);
+
+
+{ font_size: 10, font_family: 'Arial' } ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
const hsh = { font_size: 10, font_family: 'Arial' }
+for (const key in hsh) {
+ const value = hsh[key];
+ console.log(key, value);
+}
+
+
+font_size 10 +font_family Arial ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log('font_size' in options);
+
+
+true ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(options.font_size);
+
+
+10 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
const options = { font_size: 10, font_family: 'Arial' };
+console.log(Object.keys(options).length);
+
+
+2 ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
const try_it = true;
+if (try_it) console.log('Garlic gum is not funny');
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
const COST = 100;
+COST = 50;
+console.log(COST);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2 +COST = 50; + ^ + +TypeError: Assignment to constant variable. + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/other-structure-constant.js:2:6) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 + +Node.js v18.17.0 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
const Colors = Object.freeze({
+ RED: '#FF0000',
+ GREEN: '#00FF00'
+});
+console.log(Colors.GREEN);
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
puts 'Hello' if true
+
+
+Hello ++
if (true) console.log('Hello');
+
+
+Hello ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
if (true) {
+ console.log('work');
+} else {
+ console.log('sleep');
+}
+
+
+work ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
if (true && false) console.log('no');
+if (true || false) console.log('yes');
+
+
+yes ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
const foo = 'Hello!';
+switch (foo) {
+ case 10: case 20:
+ console.log('10 or 20');
+ break;
+ case 'And': console.log('case in one line'); break;
+ default:
+ console.log(`You gave me '${foo}'`);
+}
+
+
+You gave me 'Hello!' ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
puts false ? 'no' : 'yes'
+
+
+yes ++
console.log(false ? 'no' : 'yes');
+
+
+yes ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
for (let i = 1; i < 4; i++)
+ console.log(`${i}. Hi`);
+
+
+1. Hi +2. Hi +3. Hi ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
for (let i = 0; i < 6; i += 2) {
+ console.log(i);
+}
+
+
+0 +2 +4 ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
for (let i of Array(3).keys()) {
+ console.log('Hi');
+}
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
let i = 0;
+while (i < 3)
+ i += 1;
+console.log(i);
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
let i = 0;
+while (i !== 3) i += 1;
+console.log(i);
+
+
+3 ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
const greetings = Array(3).fill().map((_, i) => `${i + 1}. Hello!`);
+console.log(greetings);
+
+
+[ '1. Hello!', '2. Hello!', '3. Hello!' ] ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
for (let i = 0; i < 3; i++) {
+ console.log(`${i + 1}. Hi`);
+ if (i === 1) break;
+}
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
for (let i = 0; i < 3; i++) {
+ if (i === 1) continue;
+ console.log(`${i + 1}. Hi`);
+}
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
const arr = [1, 2, 3];
+console.log(Math.min.apply(this, arr));
+console.log(Math.max.apply(this, arr));
+
+
+1 +3 ++
puts Math.sqrt(9)
+
+
+3.0 ++
console.log(Math.sqrt(9));
+
+
+3 ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
try {
+ age++;
+} catch (error) {
+ console.log("Can't change undefined variable");
+} finally {
+ console.log("But that's ok");
+}
+
+
+Can't change undefined variable +But that's ok ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
try {
+ age++;
+} catch (error) {
+ console.log(error.message);
+}
+
+
+age is not defined ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
try {
+ throw new Error('An error!');
+} catch (e) {
+ console.log(e.message);
+}
+
+
+An error! ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
const fs = require('fs');
+const path = require('path');
+const file_path = path.join(process.cwd(), 'code', 'file.txt');
+console.log(fs.readFileSync(file_path, 'utf8'));
+
+
+Hello +World + ++
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+const fs = require('fs');
+const path = require('path');
+const file_path = path.join(__dirname, 'output.txt');
+fs.writeFile(file_path, 'Some glorious content');
+
+
+node:internal/validators:440 + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value); + ^ + +TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined + at maybeCallback (node:fs:189:3) + at Object.writeFile (node:fs:2266:14) + at Object.<anonymous> (/Users/evmorov/projects/lang-compare/code/javascript/file-write.js:4:4) + at Module._compile (node:internal/modules/cjs/loader:1256:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) + at Module.load (node:internal/modules/cjs/loader:1119:32) + at Module._load (node:internal/modules/cjs/loader:960:12) + at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) + at node:internal/main/run_main_module:23:47 { + code: 'ERR_INVALID_ARG_TYPE' +} + +Node.js v18.17.0 ++
puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
console.log(process.cwd());
+
+
+/Users/evmorov/projects/lang-compare ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
console.log(__filename);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript/file-path.js ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
console.log(__dirname);
+
+
+/Users/evmorov/projects/lang-compare/code/javascript ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
const path = require('path');
+console.log(path.join(__dirname, '..'));
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
const path = require('path');
+console.log(path.join(__dirname, '..', 'python'));
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
function hey() {
+ console.log('How are you?');
+}
+hey();
+
+
+How are you? ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
function sweets(buy, ...brands) {
+ if (buy) return console.log(brands);
+}
+sweets(true, 'snickers', 'twix', 'bounty');
+
+
+[ 'snickers', 'twix', 'bounty' ] ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
function send(abroad = false) {
+ console.log(abroad ? 'Send abroad' : 'Send locally');
+}
+send();
+send(true);
+
+
+Send locally +Send abroad ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
const multiple = (a, b) => a * b;
+console.log(multiple(2, 3));
+
+function divide(a, b) {
+ if (a === 0) return 0;
+ return a / b;
+}
+console.log(divide(0, 10));
+
+function defaultValue() {}
+console.log(defaultValue());
+
+
+6 +0 +undefined ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
const square = x => (x * x);
+console.log([2, 3].map(num => square(num)));
+
+const greeting = () => console.log('Hello World!');
+greeting();
+
+
+[ 4, 9 ] +Hello World! ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
function mySelect(arr, filter) {
+ const selected = [];
+ arr.forEach(e => {
+ if (filter(e)) selected.push(e);
+ });
+ return selected;
+}
+console.log(mySelect([1, 5, 10], x => x < 6));
+
+
+[ 1, 5 ] ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class Action {
+ static say(sentence) {
+ console.log(sentence());
+ }
+}
+
+class Person {
+ constructor(name) {
+ this.name = name;
+ }
+
+ greet() {
+ try {
+ Action.say(function() { `My name is ${this.name}!`; });
+ } catch (err) {
+ console.log(err.message);
+ }
+ Action.say(() => `My name is ${this.name}!`);
+ }
+}
+
+new Person('Alex').greet();
+
+
+Cannot read properties of undefined (reading 'name') +My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Greetings {
+ constructor() {
+ this.hi = this.hey.bind(this, true);
+ }
+
+ hey() {
+ console.log('How are you?');
+ }
+}
+
+new Greetings().hi();
+
+
+How are you? ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+new Animal().walk();
+
+
+I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal {
+ constructor(name) {
+ this.name = name;
+ }
+
+ walk() {
+ console.log(`My name is ${this.name} and I'm walking`);
+ }
+}
+
+new Animal('Kelya').walk();
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal {
+ walk() {
+ this.bark();
+ console.log("I'm walking");
+ }
+
+ bark() {
+ console.log('Wuf!');
+ }
+}
+
+new Animal().walk();
+
+
+Wuf! +I'm walking ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal {
+ static feed() {
+ console.log('Om nom nom');
+ }
+}
+
+Animal.feed();
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal {
+ take(toy) {
+ this.toy = toy;
+ }
+
+ play() {
+ console.log(`I'm playing with ${this.toy}`);
+ }
+}
+
+const animal = new Animal();
+animal.take('a ball');
+animal.play();
+
+
+I'm playing with a ball ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal {
+ setName(name) {
+ this.name = name;
+ }
+
+ getName() {
+ return this.name;
+ }
+}
+
+const animal = new Animal();
+animal.name = 'Kelya';
+console.log(animal.name);
+
+
+Kelya ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+class Dog extends Animal {
+ sing() {
+ console.log('Bark!');
+ }
+}
+
+new Dog().walk();
+
+
+I'm walking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
class Animal {
+ walk() {
+ console.log("I'm walking");
+ }
+}
+
+const animal = new Animal();
+console.log('walk' in animal);
+
+
+true ++
# it's a comment
+
+
+
+// it's a comment
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
// other-file-to-import.js
+// module.exports =
+// class Import {
+// constructor() {
+// console.log('I am imported!');
+// }
+// }
+
+const Import = require('./other-file-to-import');
+new Import();
+
+
+I am imported! ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
const [one, two] = [1, 2];
+console.log(one, two);
+
+
+1 2 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
const currentDate = new Date();
+const day = currentDate.getDate();
+const month = currentDate.getMonth() + 1;
+const year = currentDate.getFullYear();
+const date = `${year}-${month}-${day}`;
+console.log(date);
+
+
+2024-5-28 ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
console.log(new Date());
+
+
+2024-05-28T18:17:39.286Z ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
const angry = false;
+if (!angry) console.log('smile!');
+
+
+smile! ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
const exec = require('child_process').exec;
+exec('node -v', (error, stdout, stderr) => console.log(stdout));
+
+
+v18.17.0 + ++
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
<?php
+
+$greeting = "Hello World!";
+echo $greeting;
+
+
+Hello World!+
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
<?php
+
+echo "Don't worry," . " be happy";
+
+
+Don't worry, be happy+
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
<?php
+
+$first = "Don't worry,";
+$second = 'be happy';
+echo "$first $second";
+
+
+Don't worry, be happy+
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
<?php
+
+$s = "This is not funny! I am not like him!";
+$replaced = str_replace("not ", "", $s);
+echo $replaced;
+
+
+This is funny! I am like him!+
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
<?php
+
+$s = "You should work";
+$replaced = str_replace("work", "rest", $s);
+echo $replaced;
+
+
+You should rest+
puts 'I like beer'.split
+
+
+I +like +beer ++
<?php
+
+$s = "I like beer";
+$arr = explode(" ", $s);
+var_export($arr);
+
+
+array ( + 0 => 'I', + 1 => 'like', + 2 => 'beer', +)+
puts ' eh? '.strip
+
+
+eh? ++
<?php
+
+echo trim(" eh? ");
+
+eh?+
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
<?php
+
+var_dump(strcmp("string", "string") == 0);
+
+bool(true) ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
<?php
+
+var_dump(preg_match("/^b/", "apple") == 1);
+var_dump(preg_match("/^a/", "apple") == 1);
+
+
+bool(false) +bool(true) ++
i = 9
+i += 1
+puts i
+
+
+10 ++
<?php
+
+$i = 9;
+$i++;
+echo $i;
+
+
+10+
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
<?php
+
+var_dump(1 < 2 && 2 < 3);
+var_dump(5 == 5);
+var_dump(5 != 5);
+
+
+bool(true) +bool(true) +bool(false) ++
puts rand(1..2)
+
+
+1 ++
<?php
+
+echo rand(1, 2);
+
+1+
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
<?php
+
+var_dump(9 / 2);
+var_dump(9 / 2.0);
+var_dump(floor(9 / 2.0));
+var_dump(round(9 / 2.0));
+
+
+float(4.5) +float(4.5) +float(4) +float(5) ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
<?php
+
+echo gettype("hi") . "\n";
+echo gettype(new DateTime()) . "\n";
+echo get_class(new DateTime()) . "\n";
+
+
+string +object +DateTime ++
puts 10.to_f
+
+
+10.0 ++
<?php
+
+var_dump((float)10);
+
+
+float(10) ++
puts 10.to_s
+
+
+10 ++
<?php
+
+var_dump((string)10);
+
+
+string(2) "10" ++
puts '5'.to_i
+
+
+5 ++
<?php
+
+var_dump((int)"10");
+
+
+int(10) ++
puts '10'.is_a? String
+
+
+true ++
<?php
+
+var_dump(is_string("Hi"));
+var_dump(new DateTime() instanceof DateTime);
+
+
+bool(true) +bool(true) ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
<?php
+
+$notEmpty = "Not empty";
+var_dump(empty($notEmpty));
+
+$shouldBeNull = null;
+var_dump($shouldBeNull == null);
+
+$arr = [];
+var_dump(empty($arr));
+
+
+bool(false) +bool(true) +bool(true) ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
<?php
+
+$arr = ["first", "second"];
+print_r($arr);
+
+Array +( + [0] => first + [1] => second +) ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
<?php
+
+$myArr = [];
+$myArr[] = "first";
+$myArr[] = "second";
+print_r($myArr);
+
+
+Array +( + [0] => first + [1] => second +) ++
puts ['first', 1]
+
+
+first +1 ++
<?php
+
+print_r(["first", 1]);
+
+
+Array +( + [0] => first + [1] => 1 +) ++
puts [1, 2].include? 1
+
+
+true ++
<?php
+
+var_dump(in_array(2, [1, 2]));
+
+
+bool(true) ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
<?php
+
+foreach ([1, 2] as $num) {
+ var_dump($num);
+}
+
+int(1) +int(2) ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
<?php
+
+$arr = ["one", "two"];
+var_dump($arr[0]);
+var_dump($arr[count($arr) - 1]);
+
+string(3) "one" +string(3) "two" ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$first = 0;
+foreach ($arr as $n) {
+ if ($n % 2 == 0) {
+ $first = $n;
+ break;
+ }
+}
+var_dump($first);
+
+int(10) ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$filtered = array_filter($arr, function ($n) {
+ return $n % 2 == 0;
+});
+print_r($filtered);
+
+
+Array +( + [2] => 10 + [3] => 20 +) ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
<?php
+
+$arr = [1, 5, 10, 20];
+$mapped = array_map(function ($n) {
+ return $n * 2;
+}, $arr);
+print_r($mapped);
+
+Array +( + [0] => 2 + [1] => 10 + [2] => 20 + [3] => 40 +) ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
<?php
+
+$arr1 = [1, 2];
+$arr2 = [3, 4];
+$concated = array_merge($arr1, $arr2);
+print_r($concated);
+
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
<?php
+
+$arr = [4, 2, 3, 1];
+sort($arr);
+print_r($arr);
+
+Array +( + [0] => 1 + [1] => 2 + [2] => 3 + [3] => 4 +) ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
<?php
+
+$arr = [['first', 'second'], ['third', 'forth']];
+var_dump($arr[1][1]);
+
+string(5) "forth" ++
puts [1, 2, 3].size
+
+
+3 ++
<?php
+
+$arr = [1, 2, 3];
+var_dump(count($arr));
+
+int(3) ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
<?php
+
+$arr = [1, 11, 111];
+$count = 0;
+foreach ($arr as $n)
+ if ($n > 10)
+ $count++;
+var_dump($count);
+
+int(2) ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
<?php
+
+$arr = [1, 2, 3];
+$reduced = array_reduce($arr, function ($carry, $item) {
+ return $carry + $item;
+});
+print_r($reduced);
+
+6+
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
<?php
+
+$arr = ["a", "b", "c"];
+var_dump(array_search("c", $arr));
+
+int(2) ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
<?php
+
+$arr = ["a", "b", "c"];
+$key = array_search("b", $arr);
+unset($arr[$key]);
+print_r($arr);
+
+
+Array +( + [0] => a + [2] => c +) ++
puts %w(a b a).uniq
+
+
+a +b ++
<?php
+
+$arr = ["a", "b", "a"];
+$unique = array_unique($arr);
+print_r($unique);
+
+Array +( + [0] => a + [1] => b +) ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
<?php
+
+$options = [];
+$options["fontSize"] = "10";
+$options["fontFamily"] = "Arial";
+var_dump($options);
+
+array(2) { + ["fontSize"]=> + string(2) "10" + ["fontFamily"]=> + string(5) "Arial" +} ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+foreach ($options as $key => $value) {
+ echo "$key\n";
+ echo "$value\n";
+}
+
+fontSize +10 +fontFamily +Arial ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump(key_exists("fontSize", $options));
+
+bool(true) ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+var_dump($options["fontSize"]);
+
+string(2) "10" ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
<?php
+
+$options = ["fontSize" => "10", "fontFamily" => "Arial"];
+echo count($options);
+
+2+
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
<?php
+
+$tryIt = true;
+if ($tryIt)
+ echo "Garlic gum is not funny";
+
+
+Garlic gum is not funny+
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
<?php
+
+const COST = 100;
+const COST = 50;
+echo COST;
+
+
+PHP Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 + +Warning: Constant COST already defined in /Users/evmorov/projects/lang-compare/code/php/OtherStructureConstant.php on line 4 +100+
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
puts 'Hello' if true
+
+
+Hello ++
<?php
+
+if (true)
+ echo "Hello";
+
+
+Hello+
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
<?php
+
+if (true)
+ echo "work";
+else
+ echo "sleep";
+
+
+work+
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
<?php
+
+if (true && false)
+ echo "no";
+if (true || false)
+ echo "yes";
+
+
+yes+
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
<?php
+
+$s = "Hello!";
+switch ($s) {
+ case "Bye!":
+ echo "wrong";
+ break;
+ case "Hello!":
+ echo "right";
+ break;
+ default:
+ break;
+}
+
+
+right+
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
puts false ? 'no' : 'yes'
+
+
+yes ++
<?php
+
+$s = false ? "no" : "yes";
+echo $s;
+
+
+yes+
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
<?php
+
+for ($i = 1; $i <= 3; $i++)
+ echo $i . ". Hi\n";
+
+
+1. Hi +2. Hi +3. Hi ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
<?php
+
+for ($i = 0; $i <= 4; $i += 2)
+ echo $i . "\n";
+
+
+0 +2 +4 ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++)
+ echo "Hi\n";
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i < 3)
+ $i++;
+echo $i;
+
+
+3+
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
<?php
+
+$i = 0;
+while ($i != 3)
+ $i++;
+echo $i;
+
+
+3+
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ echo ($i + 1) . ". Hi\n";
+ if ($i == 1)
+ break;
+}
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
<?php
+
+for ($i = 0; $i < 3; $i++) {
+ if ($i == 1)
+ continue;
+ echo ($i + 1) . ". Hi\n";
+}
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
<?php
+
+$arr = [1, 2, 3];
+echo min($arr) . "\n";
+echo max($arr) . "\n";
+
+1 +3 ++
puts Math.sqrt(9)
+
+
+3.0 ++
<?php
+
+echo sqrt(9);
+
+
+3+
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
<?php
+
+try {
+ throw new Exception();
+} catch (Exception $e) {
+ echo "Can't divide\n";
+} finally {
+ echo "But that's ok\n";
+}
+
+
+Can't divide +But that's ok ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
<?php
+
+try {
+ throw new Exception("An error!");
+} catch (Exception $e) {
+ echo $e->getMessage();
+}
+
+
+An error!+
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
<?php
+
+$filePath = getcwd() . "/code/file.txt";
+echo file_get_contents($filePath);
+
+
+Hello +World ++
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+<?php
+
+file_put_contents(__DIR__ . "/output.txt", "Some glorious content");
+
+
+puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
<?php
+
+echo getcwd();
+
+
+/Users/evmorov/projects/lang-compare+
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
<?php
+
+echo __FILE__;
+
+
+/Users/evmorov/projects/lang-compare/code/php/FilePath.php+
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
<?php
+
+echo __DIR__;
+
+
+/Users/evmorov/projects/lang-compare/code/php+
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
<?php
+
+echo realpath(__DIR__ . "/..");
+
+
+/Users/evmorov/projects/lang-compare/code+
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
<?php
+
+echo realpath(__DIR__ . "/.." . "/ruby");
+
+
+/Users/evmorov/projects/lang-compare/code/ruby+
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
<?php
+
+function hey()
+{
+ echo "How are you?";
+}
+
+hey();
+
+
+How are you?+
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
<?php
+
+function sweets(bool $buy, string... $brands)
+{
+ if ($buy)
+ var_dump($brands);
+}
+
+sweets(true, "snickers", "twix", "bounty");
+
+array(3) { + [0]=> + string(8) "snickers" + [1]=> + string(4) "twix" + [2]=> + string(6) "bounty" +} ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
<?php
+
+function divide(int $a, int $b) : float
+{
+ if ($a == 0)
+ return 0;
+ return $a / $b;
+}
+
+echo divide(0, 10) . "\n";
+echo divide(10, 5) . "\n";
+echo divide(5, 10) . "\n";
+
+
+0 +2 +0.5 ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
<?php
+
+class AnimalC
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalC();
+$animal->walk();
+
+I'm walking+
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
<?php
+
+class AnimalB
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function walk()
+ {
+ echo "My name is {$this->name} and I'm walking";
+ }
+}
+
+$animal = new AnimalB("Kelya");
+$animal->walk();
+
+My name is Kelya and I'm walking+
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
<?php
+
+class AnimalH
+{
+ public function walk()
+ {
+ $this->bark();
+ $this->guard();
+ echo "I'm walking\n";
+ }
+
+ public function bark()
+ {
+ echo "Wuf!\n";
+ }
+
+ private function guard()
+ {
+ echo "WUUUF!\n";
+ }
+}
+
+(new AnimalH())->walk();
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
<?php
+
+class AnimalA
+{
+ public static function feed()
+ {
+ echo "Om nom nom";
+ }
+}
+
+AnimalA::feed();
+
+
+Om nom nom+
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
<?php
+
+class AnimalI
+{
+ public function eat(string $food)
+ {
+ if ($this->isMeat($food))
+ echo "Om nom nom";
+ }
+
+ private function isMeat(string $food) : bool
+ {
+ return strcmp($food, "meat") == 0;
+ }
+}
+
+(new AnimalI())->eat("meat");
+
+
+Om nom nom+
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
<?php
+
+class AnimalJ
+{
+ private $name;
+
+ public function __construct(string $name)
+ {
+ $this->name = $name;
+ $this->greet();
+ }
+
+ private function greet()
+ {
+ echo "Hello! My name is " . $this->name;
+ }
+}
+
+new AnimalJ("Kelya");
+
+
+Hello! My name is Kelya+
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
<?php
+
+class AnimalD
+{
+
+ private $toy;
+
+ public function take(string $toy)
+ {
+ $this->toy = $toy;
+ }
+
+ public function play()
+ {
+ echo "I'm playing with " . $this->toy;
+ }
+}
+
+$animal = new AnimalD();
+$animal->take("a ball");
+$animal->play();
+
+
+I'm playing with a ball+
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
<?php
+
+class AnimalE
+{
+ private $name;
+
+ public function setName(string $name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName() : string
+ {
+ return $this->name;
+ }
+}
+
+$animal = new AnimalE();
+$animal->setName("Kelya");
+echo $animal->getName();
+
+
+Kelya+
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
<?php
+
+class AnimalG
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+class Dog extends AnimalG
+{
+ public function sing()
+ {
+ echo "Bark!";
+ }
+}
+
+$dog = new Dog();
+$dog->walk();
+
+
+I'm walking+
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
<?php
+
+class AnimalF
+{
+ public function walk()
+ {
+ echo "I'm walking";
+ }
+}
+
+$animal = new AnimalF();
+$hasMethod = method_exists($animal, "walk");
+var_dump($hasMethod);
+
+
+bool(true) ++
# it's a comment
+
+
+
+<?php
+
+// it's a comment
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
<?php
+
+// OtherFileToImport.php
+// <?php
+// echo "I am imported!";
+
+include "OtherFileToImport.php";
+
+
+I am imported!+
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
<?php
+
+echo (new DateTime())->format("Y-m-d");
+
+
+2024-05-28+
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
<?php
+
+echo (new DateTime())->format("m/d/y h:i A");
+
+
+05/28/24 06:22 PM+
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
<?php
+
+$angry = false;
+if (!$angry)
+ echo "smile!";
+
+
+smile!+
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
<?php
+
+$output = [];
+exec("php --version", $output);
+echo $output[0];
+
+PHP 8.2.8 (cli) (built: Jul 6 2023 11:16:57) (NTS)+
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
greeting = 'Hello World!'
+print(greeting)
+
+
+Hello World! ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
print("Don't worry," + ' be happy')
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+print('%s %s' % (first, second))
+
+
+Don't worry, be happy ++[ 3.6 ]
first = "Don't worry,"
+second = 'be happy'
+print(f'{first} {second}')
+
+
+Don't worry, be happy ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
print('This is not funny! I am not like him!'.replace('not ', ''))
+
+
+This is funny! I am like him! ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
print('You should work'.replace('work', 'rest'))
+
+
+You should rest ++
puts 'I like beer'.split
+
+
+I +like +beer ++
print('I like beer'.split())
+
+
+['I', 'like', 'beer'] ++
puts ' eh? '.strip
+
+
+eh? ++
print(' eh? '.strip())
+
+
+eh? ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
print('string' == 'string')
+print('string' != 'string')
+
+
+True +False ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
import re
+
+print(re.search('^b', 'apple'))
+print(re.search('^a', 'apple'))
+
+
+None +<re.Match object; span=(0, 1), match='a'> ++
i = 9
+i += 1
+puts i
+
+
+10 ++
i = 9
+i += 1
+print(i)
+
+
+10 ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
print(1 < 2 < 3)
+print(5 == 5)
+print(5 != 5)
+
+
+True +True +False ++
puts rand(1..2)
+
+
+1 ++
import random
+
+print(random.randint(1, 2))
+
+
+2 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
import math
+
+print(9 // 2)
+print(9 / 2)
+print(math.floor(9 / 2))
+print(round(9 / 2)) # rounds half to even
+
+
+4 +4.5 +4 +4 ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
print(type('hi'))
+print(type(1))
+
+
+<class 'str'> +<class 'int'> ++
puts 10.to_f
+
+
+10.0 ++
print(float(10))
+
+
+10.0 ++
puts 10.to_s
+
+
+10 ++
print(str(10))
+
+
+10 ++
puts '5'.to_i
+
+
+5 ++
print(int('5'))
+
+
+5 ++
puts '10'.is_a? String
+
+
+true ++
print(isinstance('10', str))
+
+
+True ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
def check(label, fn, values):
+ print(label)
+ for value in values:
+ try:
+ result = 'true' if fn(value) else 'false'
+ except TypeError as e:
+ result = 'error: %s' % e
+ print(" %-9r - %s" % (value, result))
+ print()
+
+values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]
+
+check('if value:', lambda v: v, values)
+check('if value is None:', lambda v: v is None, values)
+check('if len(value):', lambda v: len(v), values)
+
+
+if value: + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - true + 0 - false + True - true + False - false + None - false + +if value is None: + 'string' - false + '' - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + True - false + False - false + None - true + +if len(value): + 'string' - true + '' - false + [1, 2, 3] - true + [] - false + 5 - error: object of type 'int' has no len() + 0 - error: object of type 'int' has no len() + True - error: object of type 'bool' has no len() + False - error: object of type 'bool' has no len() + None - error: object of type 'NoneType' has no len() + ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
arr = ['first', 'second']
+print(arr)
+
+
+['first', 'second'] ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
arr = []
+arr.append('first')
+arr.append('second')
+print(arr)
+
+
+['first', 'second'] ++
puts ['first', 1]
+
+
+first +1 ++
print(['first', 1])
+
+
+['first', 1] ++
puts [1, 2].include? 1
+
+
+true ++
print(1 in [1, 2])
+
+
+True ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
for num in [1, 2]:
+ print(num)
+
+
+1 +2 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
for i, num in enumerate(['one', 'two']):
+ print(num)
+ print(i)
+
+
+one +0 +two +1 ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
arr = ['one', 'two']
+print(arr[0])
+print(arr[-1])
+
+
+one +two ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
arr = [1, 5, 10, 20]
+print(next(i for i in arr if i % 2 == 0))
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
arr = [1, 5, 10, 20]
+print([i for i in arr if i % 2 == 0])
+
+
+[10, 20] ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
arr = [1, 5, 10, 20]
+print([num * 2 for num in arr])
+
+
+[2, 10, 20, 40] ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
print([1, 2] + [3, 4])
+
+
+[1, 2, 3, 4] ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
print(sorted([4, 2, 3, 1]))
+
+
+[1, 2, 3, 4] ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
multi = [['first', 'second'], ['third', 'forth']]
+print(multi[1][1])
+
+
+forth ++
puts [1, 2, 3].size
+
+
+3 ++
print(len([1, 2, 3]))
+
+
+3 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
arr = [1, 11, 111]
+print(sum(1 for i in arr if i > 10))
+
+
+2 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
import functools, operator
+
+print(functools.reduce(operator.add, [1, 2, 3]))
+print(sum([1, 2, 3])) # a more Pythonic example
+
+
+6 +6 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
print(['a', 'b', 'c'].index('c'))
+
+
+2 ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
arr = ['a', 'b', 'c']
+arr.remove('b')
+print(arr)
+
+
+['a', 'c'] ++
puts %w(a b a).uniq
+
+
+a +b ++
print(set(['a', 'b', 'a']))
+
+
+{'a', 'b'} ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
options = {}
+options['font_size'] = 10
+options['font_family'] = 'Arial'
+print(options)
+
+
+{'font_size': 10, 'font_family': 'Arial'} ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
+ print(key, value)
+
+
+font_size 10 +font_family Arial ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print('font_size' in options)
+
+
+True ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(options['font_size'])
+
+
+10 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
options = {'font_size': 10, 'font_family': 'Arial'}
+print(len(options))
+
+
+2 ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
try_it = True
+if try_it:
+ print('Garlic gum is not funny')
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
COST = 100
+COST = 50
+print(COST)
+
+
+50 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
class Colors:
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+
+print(Colors.GREEN)
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
import collections
+
+class Customer(collections.namedtuple('Customer', 'name address')):
+ def greeting(self):
+ return "Hello %s!" % self.name
+
+print(Customer('Dave', '123 Main').greeting())
+
+
+Hello Dave! ++
puts 'Hello' if true
+
+
+Hello ++
if True:
+ print('Hello')
+
+
+Hello ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
if True:
+ print('work')
+else:
+ print('sleep')
+
+
+work ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
if True and False:
+ print('no')
+if True or False:
+ print('yes')
+
+
+yes ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
foo = 'Hello!'
+if foo in range(1, 6):
+ print("It's between 1 and 5")
+elif foo in (10, 20):
+ print('10 or 20')
+elif foo == 'And':
+ print('case in one line')
+elif isinstance(foo, str):
+ print("You passed a string %r" % foo)
+else:
+ print("You gave me %r" % foo)
+
+
+You passed a string 'Hello!' ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
score = 76
+grades = [
+ (60, 'F'),
+ (70, 'D'),
+ (80, 'C'),
+ (90, 'B'),
+]
+print(next((g for x, g in grades if score < x), 'A'))
+
+
+C ++
puts false ? 'no' : 'yes'
+
+
+yes ++
print('no' if False else 'yes')
+
+
+yes ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
result = 'a' if True else 'b'
+print(result)
+
+
+a ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
for i in range(1, 4):
+ print('%d. Hi' % i)
+
+
+1. Hi +2. Hi +3. Hi ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
for i in range(0, 5, 2):
+ print(i)
+
+
+0 +2 +4 ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
for i in range(3):
+ print('Hi')
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
i = 0
+while i < 3:
+ i += 1
+print(i)
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
i = 0
+while i != 3:
+ i += 1
+print(i)
+
+
+3 ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
greetings = ["%d. Hello!" % time for time in range(1, 4)]
+print(greetings)
+
+
+['1. Hello!', '2. Hello!', '3. Hello!'] ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
for time in range(1, 4):
+ print("%d. Hi" % time)
+ if time == 2:
+ break
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
for time in range(1, 4):
+ if time == 2:
+ continue
+ print("%d. Hi" % time)
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
arr = [1, 2, 3]
+print(min(arr))
+print(max(arr))
+
+
+1 +3 ++
puts Math.sqrt(9)
+
+
+3.0 ++
import math
+
+print(math.sqrt(9))
+
+
+3.0 ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
try:
+ 1 / 0
+except:
+ print("Can't divide")
+finally:
+ print("But that's ok")
+
+
+Can't divide +But that's ok ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
try:
+ 1 / 0
+except Exception as e:
+ print(e)
+
+
+division by zero ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
def divide(num1, num2):
+ try:
+ num1 / num2
+ except Exception as e:
+ print(e)
+divide(1, 0)
+
+
+division by zero ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
try:
+ raise Exception('An error!')
+except Exception as e:
+ print(e)
+
+
+An error! ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
import os
+
+with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
+ print(f.read())
+
+
+Hello +World + ++
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+import pathlib
+
+with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
+ f.write('Some glorious content')
+
+
+
+puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
import os
+
+print(os.getcwd())
+
+
+/Users/evmorov/projects/lang-compare ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
print(__file__)
+
+
+/Users/evmorov/projects/lang-compare/code/python/file_path.py ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
import pathlib
+
+print(pathlib.Path(__file__).parent)
+
+
+/Users/evmorov/projects/lang-compare/code/python ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1])
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
import pathlib
+
+print(pathlib.Path(__file__).parents[1] / 'ruby')
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
def hey():
+ print('How are you?')
+hey()
+
+
+How are you? ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
def sweets(buy, *brands):
+ if buy:
+ print(brands)
+sweets(True, 'snickers', 'twix', 'bounty')
+
+
+('snickers', 'twix', 'bounty') ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
def send(abroad=False):
+ print('Send abroad' if abroad else 'Send locally')
+send()
+send(True)
+
+
+Send locally +Send abroad ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
def multiply(a, b):
+ return a * b
+
+def divide(a, b):
+ return 0 if a == 0 else a / b
+
+def default_value():
+ pass
+
+print(multiply(2, 3))
+print(divide(0, 10))
+print(default_value())
+
+
+6 +0 +None ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
square = lambda x: x * x
+print(list(map(square, [2, 3])))
+
+greeting = lambda: print('Hello World!')
+greeting()
+
+
+[4, 9] +Hello World! ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
def select(arr):
+ yield from arr
+
+def select_filter(arr, filter):
+ for a in arr:
+ if filter(a):
+ yield a
+
+print([x for x in select([1, 5, 10]) if x < 6])
+print(list(select_filter([1, 5, 10], lambda x: x < 6)))
+
+
+[1, 5] +[1, 5] ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class Action:
+ name = 'Ann'
+
+ @staticmethod
+ def say(sentence):
+ print(sentence())
+
+
+class Person:
+ def __init__(self, name):
+ self.name = name
+
+ def greet(self):
+ Action.say(lambda: "My name is %s!" % self.name)
+
+
+Person('Alex').greet()
+
+
+My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class ProccessElements:
+ def __init__(self):
+ def element(el_name):
+ def render(content):
+ return '<{0}>{1}</{0}>'.format(el_name, content)
+ return render
+
+ for el_name in self.elements:
+ setattr(self, el_name, element(el_name))
+
+
+class HtmlELements(ProccessElements):
+ elements = ('div', 'span')
+
+print(HtmlELements().div('hello'))
+
+
+<div>hello</div> ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Greetings:
+ def hey(self):
+ print('How are you?')
+ hi = hey
+
+Greetings().hi()
+
+
+How are you? ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+Animal().walk()
+
+
+I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+
+ def walk(self):
+ print("My name is %s and I'm walking" % self.name)
+
+Animal('Kelya').walk()
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal:
+ def walk(self):
+ self.bark()
+ self._guard()
+ print("I'm walking")
+
+ def bark(self):
+ print('Wuf!')
+
+ # Private by convention
+ def _guard(self):
+ print('WUUUF!')
+
+Animal().walk()
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal:
+ @classmethod
+ def feed(cls):
+ print('Om nom nom')
+
+Animal.feed()
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal:
+ def eat(self, food):
+ if self._is_meat(food):
+ print('Om nom nom')
+
+ def _is_meat(self, food):
+ return food == 'meat'
+
+Animal().eat('meat')
+
+
+Om nom nom ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal:
+ def __init__(self, name):
+ self.name = name
+ self._greet()
+
+ def _greet(self):
+ print("Hello! My name is %s" % self.name)
+
+Animal('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal:
+ def take(self, toy):
+ self.toy = toy
+
+ def play(self):
+ print("I'm playing with %s" % self.toy)
+
+animal = Animal()
+animal.take('a ball')
+animal.play()
+
+
+I'm playing with a ball ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal:
+ name = None
+
+animal = Animal()
+animal.name = 'Kelya'
+print(animal.name)
+
+
+Kelya ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+class Dog(Animal):
+ def sing(self):
+ print('Bark!')
+
+Dog().walk()
+
+
+I'm walking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
class Moving:
+ def walk(self):
+ print("%s is walking" % self.__class__.__name__)
+
+class Interacting:
+ def talk(self):
+ print("%s is talking" % self.__class__.__name__)
+
+class Human(Moving, Interacting):
+ pass
+
+human = Human()
+human.walk()
+human.talk()
+
+
+Human is walking +Human is talking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
class Animal:
+ def walk(self):
+ print("I'm walking")
+
+animal = Animal()
+print(hasattr(animal, 'walk'))
+
+
+True ++
# it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
speed = 0
+speed = 15 if speed is None else speed
+print(speed)
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
# other_file_to_import.py
+# class Import:
+# def __init__(self):
+# print('I am imported!')
+
+import other_file_to_import
+other_file_to_import.Import()
+
+
+I am imported! ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
one, two = 1, 2
+print(one, two)
+
+
+1 2 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
import datetime
+print(datetime.date.today())
+
+
+2024-05-28 ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
import datetime
+print(datetime.datetime.now())
+
+
+2024-05-28 20:18:14.644332 ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
angry = False
+if not angry:
+ print('smile!')
+
+
+smile! ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
yeti = None
+footprints = yeti or 'bear'
+print(footprints)
+
+
+bear ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
import subprocess
+subprocess.call(['python3', '--version'])
+
+
+Python 3.11.2 ++
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
greeting = 'Hello World!'
+puts greeting
+
+
+Hello World! ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
puts "Don't worry," + ' be happy'
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
first = "Don't worry,"
+second = 'be happy'
+puts "#{first} #{second}"
+
+
+Don't worry, be happy ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
puts 'This is not funny! I am not like him!'.gsub('not ', '')
+
+
+This is funny! I am like him! ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
puts 'You should work'.gsub('work', 'rest')
+
+
+You should rest ++
puts 'I like beer'.split
+
+
+I +like +beer ++
puts 'I like beer'.split
+
+
+I +like +beer ++
puts ' eh? '.strip
+
+
+eh? ++
puts ' eh? '.strip
+
+
+eh? ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
puts 'string' == 'string'
+puts 'string' != 'string'
+
+
+true +false ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
p 'apple' =~ /^b/
+p 'apple' =~ /^a/
+
+
+nil +0 ++
i = 9
+i += 1
+puts i
+
+
+10 ++
i = 9
+i += 1
+puts i
+
+
+10 ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
puts 1 < 2 && 2 < 3
+puts 5 == 5
+puts 5 != 5
+
+
+true +true +false ++
puts rand(1..2)
+
+
+1 ++
puts rand(1..2)
+
+
+1 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
puts 9 / 2
+puts 9 / 2.0
+puts (9 / 2.0).floor
+puts (9 / 2.0).round
+
+
+4 +4.5 +4 +5 ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
puts 'hi'.class
+puts 1.class
+
+
+String +Fixnum ++
puts 10.to_f
+
+
+10.0 ++
puts 10.to_f
+
+
+10.0 ++
puts 10.to_s
+
+
+10 ++
puts 10.to_s
+
+
+10 ++
puts '5'.to_i
+
+
+5 ++
puts '5'.to_i
+
+
+5 ++
puts '10'.is_a? String
+
+
+true ++
puts '10'.is_a? String
+
+
+true ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
def check(label, fn, values)
+ puts label
+ values.each do |value|
+ begin
+ result = fn.call(value) ? 'true' : 'false'
+ rescue NoMethodError => e
+ result = "error: #{e}"
+ end
+ puts format(" %-9p - %s", value, result)
+ end
+ puts ''
+end
+
+values = ['string', '', [1, 2, 3], [], 5, 0, true, false, nil]
+
+check('if value:', -> (v) { v }, values)
+check('if value.nil?:', -> (v) { v.nil? }, values)
+check('if value.empty?:', -> (v) { v.empty? }, values)
+
+
+if value: + "string" - true + "" - true + [1, 2, 3] - true + [] - true + 5 - true + 0 - true + true - true + false - false + nil - false + +if value.nil?: + "string" - false + "" - false + [1, 2, 3] - false + [] - false + 5 - false + 0 - false + true - false + false - false + nil - true + +if value.empty?: + "string" - false + "" - true + [1, 2, 3] - false + [] - true + 5 - error: undefined method `empty?' for 5:Fixnum + 0 - error: undefined method `empty?' for 0:Fixnum + true - error: undefined method `empty?' for true:TrueClass + false - error: undefined method `empty?' for false:FalseClass + nil - error: undefined method `empty?' for nil:NilClass + ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
arr = %w(first second)
+puts arr
+
+
+first +second ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
arr = []
+arr.push 'first'
+arr.push 'second'
+puts arr
+
+
+first +second ++
puts ['first', 1]
+
+
+first +1 ++
puts ['first', 1]
+
+
+first +1 ++
puts [1, 2].include? 1
+
+
+true ++
puts [1, 2].include? 1
+
+
+true ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
[1, 2].each do |num|
+ puts num
+end
+
+
+1 +2 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
%w(one two).each_with_index do |num, i|
+ puts num
+ puts i
+end
+
+
+one +0 +two +1 ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
arr = %w(one two)
+puts arr.first
+puts arr.last
+
+
+one +two ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.find(&:even?)
+
+
+10 ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
arr = [1, 5, 10, 20]
+puts arr.select(&:even?)
+
+
+10 +20 ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
arr = [1, 5, 10, 20]
+puts arr.map { |num| num * 2 }
+
+
+2 +10 +20 +40 ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
puts [1, 2] + [3, 4]
+
+
+1 +2 +3 +4 ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
puts [4, 2, 3, 1].sort
+
+
+1 +2 +3 +4 ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
multi = [%w(first second), %w(third forth)]
+puts multi[1][1]
+
+
+forth ++
puts [1, 2, 3].size
+
+
+3 ++
puts [1, 2, 3].size
+
+
+3 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
arr = [1, 11, 111]
+puts arr.count { |i| i > 10 }
+
+
+2 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
puts [1, 2, 3].reduce(:+)
+
+
+6 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
puts ['a', 'b', 'c'].index('c')
+
+
+2 ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
arr = %w(a b c)
+arr.delete('b')
+puts arr
+
+
+a +c ++
puts %w(a b a).uniq
+
+
+a +b ++
puts %w(a b a).uniq
+
+
+a +b ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
options = { font_size: 10, font_family: 'Arial' }
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
options = {}
+options[:font_size] = 10
+options[:font_family] = 'Arial'
+puts options
+
+
+{:font_size=>10, :font_family=>"Arial"} ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
{ font_size: 10, font_family: 'Arial' }.each do |key, value|
+ puts key, value
+end
+
+
+font_size +10 +font_family +Arial ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.include? :font_size
+
+
+true ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options[:font_size]
+
+
+10 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
options = { font_size: 10, font_family: 'Arial' }
+puts options.size
+
+
+2 ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
try_it = true
+puts 'Garlic gum is not funny' if try_it
+
+
+Garlic gum is not funny ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
COST = 100
+COST = 50
+puts COST
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:2: warning: already initialized constant COST +/Users/evmorov/projects/lang-compare/code/ruby/other_structure_constant.rb:1: warning: previous definition of COST was here +50 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
module Colors
+ RED = '#FF0000'
+ GREEN = '#00FF00'
+end
+puts Colors::GREEN
+
+
+#00FF00 ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
Customer = Struct.new(:name, :address) do
+ def greeting
+ "Hello #{name}!"
+ end
+end
+puts Customer.new('Dave', '123 Main').greeting
+
+
+
+Hello Dave! ++
puts 'Hello' if true
+
+
+Hello ++
puts 'Hello' if true
+
+
+Hello ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
angry = false
+puts 'smile!' unless angry
+
+
+smile! ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
if true
+ puts 'work'
+else
+ puts 'sleep'
+end
+
+
+work ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
puts 'no' if true && false
+puts 'yes' if true || false
+
+
+yes ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
foo = 'Hello!'
+case foo
+when 1..5
+ puts "It's between 1 and 5"
+when 10, 20
+ puts '10 or 20'
+when 'And' then puts 'case in one line'
+when String
+ puts "You passed a string '#{foo}'"
+else
+ puts "You gave me '#{foo}'"
+end
+
+
+You passed a string 'Hello!' ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
score = 76
+grade = case
+ when score < 60 then 'F'
+ when score < 70 then 'D'
+ when score < 80 then 'C'
+ when score < 90 then 'B'
+ else 'A'
+ end
+puts grade
+
+
+C ++
puts false ? 'no' : 'yes'
+
+
+yes ++
puts false ? 'no' : 'yes'
+
+
+yes ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
result =
+if true
+ 'a'
+else
+ 'b'
+end
+puts result
+
+
+
+a ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
(1..3).each do |i|
+ puts "#{i}. Hi"
+end
+
+
+1. Hi +2. Hi +3. Hi ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
(0..4).step(2) do |i|
+ puts i
+end
+
+
+0 +2 +4 ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
3.times do
+ puts 'Hi'
+end
+
+
+Hi +Hi +Hi ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
i = 0
+while i < 3
+ i += 1
+end
+puts i
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
i = 0
+i += 1 until i == 3
+puts i
+
+
+3 ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
greetings = Array.new(3) do |i|
+ "#{i + 1}. Hello!"
+end
+puts greetings
+
+
+1. Hello! +2. Hello! +3. Hello! ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ puts "#{time + 1}. Hi"
+ break if time == 1
+end
+
+
+1. Hi +2. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
3.times do |time|
+ next if time == 1
+ puts "#{time + 1}. Hi"
+end
+
+
+1. Hi +3. Hi ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
arr = [1, 2, 3]
+puts arr.min
+puts arr.max
+
+
+1 +3 ++
puts Math.sqrt(9)
+
+
+3.0 ++
puts Math.sqrt(9)
+
+
+3.0 ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
begin
+ 1 / 0
+rescue
+ puts "Can't divide"
+ensure
+ puts "But that's ok"
+end
+
+1 / 0 rescue puts "Can't divide"
+
+
+Can't divide +But that's ok +Can't divide ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
begin
+ 1 / 0
+rescue => e
+ puts e.message
+end
+
+
+divided by 0 ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
def divide(num1, num2)
+ num1 / num2
+rescue => e
+ puts e.message
+end
+divide(1, 0)
+
+
+divided by 0 ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
begin
+ fail 'An error!'
+rescue => e
+ puts e.message
+end
+
+
+An error! ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
file_path = File.join(Dir.getwd, 'code', 'file.txt')
+puts File.read(file_path)
+
+
+Hello +World ++
file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+file_path = File.join(File.dirname(__FILE__), 'output.txt')
+File.write(file_path, 'Some glorious content')
+
+
+
+puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
puts Dir.getwd
+
+
+/Users/evmorov/projects/lang-compare ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
puts __FILE__
+
+
+/Users/evmorov/projects/lang-compare/code/ruby/file_path.rb ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
puts File.dirname(__FILE__)
+
+
+/Users/evmorov/projects/lang-compare/code/ruby ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..')
+
+
+/Users/evmorov/projects/lang-compare/code ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
puts File.expand_path File.join(__FILE__, '..', '..', 'php')
+
+
+
+/Users/evmorov/projects/lang-compare/code/php ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
def hey
+ puts 'How are you?'
+end
+hey
+
+
+How are you? ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
def sweets(buy, *brands)
+ puts brands if buy
+end
+sweets true, 'snickers', 'twix', 'bounty'
+
+
+snickers +twix +bounty ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
def send(abroad = false)
+ puts abroad ? 'Send abroad' : 'Send locally'
+end
+send
+send true
+
+
+Send locally +Send abroad ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
def multiple(a, b)
+ a * b
+end
+puts multiple(2, 3)
+
+def divide(a, b)
+ return 0 if a == 0
+ a / b
+end
+puts divide 0, 10
+
+def default_value
+end
+p default_value
+
+
+6 +0 +nil ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
square = -> (x) { x * x }
+puts [2, 3].map(&square)
+
+greeting = -> { puts 'Hello World!' }
+greeting.call
+
+
+4 +9 +Hello World! ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
def my_select(arr)
+ selected = []
+ arr.each do |a|
+ selected.push a if yield(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+def my_select(arr, &filter)
+ selected = []
+ arr.each do |a|
+ selected.push a if filter.call(a)
+ end
+ selected
+end
+puts my_select [1, 5, 10] { |x| x < 6 }
+
+
+1 +5 +1 +5 ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class Action
+ def self.say(&sentence)
+ @name = 'Ann'
+ puts sentence.call
+ end
+end
+
+class Person
+ def initialize(name)
+ @name = name
+ end
+
+ def greet
+ Action.say { "My name is #{@name}!" }
+ end
+end
+
+Person.new('Alex').greet
+
+
+My name is Alex! ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class ProccessElements
+ def self.element(el_name)
+ define_method "#{el_name}_element" do |content|
+ "<#{el_name}>#{content}</#{el_name}>"
+ end
+ end
+end
+
+class HtmlELements < ProccessElements
+ element :div
+ element :span
+end
+
+puts HtmlELements.new.div_element('hello')
+
+
+<div>hello</div> ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Greetings
+ def hey
+ puts 'How are you?'
+ end
+ alias_method :hi, :hey
+end
+
+Greetings.new.hi
+
+
+How are you? ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+Animal.new.walk
+
+
+I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def initialize(name)
+ @name = name
+ end
+
+ def walk
+ puts "My name is #{@name} and I'm walking"
+ end
+end
+
+Animal.new('Kelya').walk
+
+
+My name is Kelya and I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def walk
+ bark
+ guard
+ puts "I'm walking"
+ end
+
+ def bark
+ puts 'Wuf!'
+ end
+
+ private
+
+ def guard
+ puts 'WUUUF!'
+ end
+end
+
+Animal.new.walk
+
+
+Wuf! +WUUUF! +I'm walking ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal
+ def self.feed
+ puts 'Om nom nom'
+ end
+end
+
+Animal.feed
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal
+ def eat(food)
+ puts 'Om nom nom' if meat? food
+ end
+
+ private
+
+ def meat?(food)
+ food == 'meat'
+ end
+end
+
+Animal.new.eat('meat')
+
+
+Om nom nom ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal
+ def initialize(name)
+ @name = name
+ greet
+ end
+
+ private
+
+ def greet
+ puts "Hello! My name is #{@name}"
+ end
+end
+
+Animal.new('Kelya')
+
+
+Hello! My name is Kelya ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal
+ def take(toy)
+ @toy = toy
+ end
+
+ def play
+ puts "I'm playing with #{@toy}"
+ end
+end
+
+animal = Animal.new
+animal.take('a ball')
+animal.play
+
+
+I'm playing with a ball ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal
+ attr_accessor :name
+end
+
+animal = Animal.new
+animal.name = 'Kelya'
+puts animal.name
+
+
+Kelya ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+class Dog < Animal
+ def sing
+ puts 'Bark!'
+ end
+end
+
+Dog.new.walk
+
+
+I'm walking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
module Moving
+ def walk
+ puts "#{self.class.name} is walking"
+ end
+end
+
+module Interacting
+ def talk
+ puts "#{self.class.name} is talking"
+ end
+end
+
+class Human
+ include Moving
+ include Interacting
+end
+
+human = Human.new
+human.walk
+human.talk
+
+
+Human is walking +Human is talking ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
class Animal
+ def walk
+ puts "I'm walking"
+ end
+end
+
+animal = Animal.new
+puts animal.respond_to? :walk
+
+
+true ++
# it's a comment
+
+
+
+# it's a comment
+
+
+
+speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
speed = 0
+speed ||= 15
+puts speed
+
+
+0 ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
class Winner
+ attr_reader :address
+
+ def initialize
+ # @address = Address.new
+ end
+end
+
+class Address
+ attr_reader :zipcode
+
+ def initialize
+ @zipcode = 192187
+ end
+end
+
+zip = Winner.new.address&.zipcode
+puts zip ? "Zipcode is #{zip}" : "No prize without zipcode"
+
+
+No prize without zipcode ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
# other_file_to_import.rb
+# class Import
+# def initialize
+# puts 'I am imported!'
+# end
+# end
+
+require_relative 'other_file_to_import'
+Import.new
+
+
+I am imported! ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
one, two = [1, 2]
+puts one, two
+
+
+1 +2 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
require 'date'
+puts Date.today
+
+
+2024-05-28 ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
puts Time.now
+
+
+2024-05-28 20:17:54 +0200 ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
angry = false
+puts 'smile!' if !angry
+
+
+smile! ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
yeti = nil
+footprints = yeti || 'bear'
+puts footprints
+
+
+bear ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++
puts `ruby -v`
+
+
+ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin21] ++