Eating and comparing programming languages: Python and Ruby

Introduction

This article is for comparing what happens if you write the same behavior in Python and Ruby.

Please note that it may be awkward because it is written as a memorandum.

Dialogue console

Use the python command in Python and the irb in Ruby.

Python


$ python
Python 3.8.5 ...
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Ruby


$ irb
irb(main):001:0> 

When exiting the interactive console For Python, exit () or Ctrl + Z (for Windows), Ctrl + D (for Linux), For Ruby, exit or Ctrl + D You can get out of the dialogue console with

Write Hello World!

Python is print, Ruby is puts.

Python


print("Hello World!")

Ruby


puts "Hello World!"

Branch

There is no big difference in writing style between the two, Python needs to be indented in if, and Ruby must add end at the end of the definition Note that when providing else if, Python iselif [expression]:and Ruby iselsif [expression].

Python


a = 1

if a == 1:
    print("a is 1")
elif a == 2:
    print("a is 2")
else:
    print("a is neither 1 nor 2")

Ruby


a = 1

if a == 1
  puts "a is 1"
elsif a == 2
  puts "a is 2"
else
  puts "a is neither 1 nor 2"
end

Repeat (repetition)

Use for for Python and each for Ruby if it is repeated by an array etc.

Python


for a in range(10):
    print(a)

Ruby


(0..9).each do |a|
  puts a
end

Function definition

With no arguments

It looks like this in Python

Python


def func_def():
    print("It's function")
    
if __name__ == "__main__":
    func_def()

In case of Python, it is necessary to add () even if there is no argument (behavior is different with and without)

With Ruby

Ruby


def func_def
  puts "It's function"
end

if __FILE__ == $0
  func_def # func_def()the same as
end

In the case of Ruby, it is not necessary to add () if there is no argument (it works even if it is added)

With arguments

This doesn't change much either.

Python


def arg_func(one, two=2):
    print(f"one: {one}, two: {two}")

if __name__ == "__main__":
    arg_func(1)

Ruby


def arg_func (one, two=2)
  puts "one: #{one}, two: #{two}"
end

if __FILE__ == $0
  arg_func(1)
end

As an aside,

For Python if __name__ ==" __main__ ":, In the case of Ruby, if __FILE__ == $ 0 can be used to determine whether it is treated as the main file.

Also, Python is f" {variables} ", Ruby can assign each variable to a string with " # {variables} "

class

Both Python and Ruby have the concept of classes However, the usability is slightly different when comparing the two.

Definition

Class constructor is defined with __init__ for Python and initialize for Ruby.

Python


class Greeter:
    def __init__(self, name="World"):
        self.name = name

    def hello(self):
        print(f"Hello {self.name}!")

    def evening(self):
        print(f"Good evening {self.name}!")

Ruby


class Greeter
  def initialize(name = "World")
    @name = name
  end

  def hello
    puts "Hello #{@name}!"
  end

  def evening
    puts "Good evening #{@name}!"
  end
end

Ruby variables can be read by doing attr_accessor: [instance variable] Anyway, it's no exaggeration to say that instance variables will be treated as private if this is not set. Note that Python will be treated as private if you add __ (two underscores) to the beginning of the variable (same for functions).

Also, if you set the same class in Python, it will be replaced, In the case of Ruby, you can add it by writing the same class again. (And it also applies to instances that have already been created)

Ruby


# -- snip -- (Suppose the above Greeter class is already defined)
class Greeter
  attr_accessor :name
end

Instance creation

To create an instance, Python uses the class name as it is, and Ruby uses .new in addition to the class name.

Python


# -- snip --
greet = Greeter("Qiita")

Ruby


# -- snip --
greet = Greeter.new("Qiita")

Finally

--Python and Ruby are similar where they are similar --Python is a processing description such as branching by indentation --In Ruby, the process description is up to end, so you can see the delimiter.

Ruby memos are summarized in Scrapbox (Yuzulia-Prog Builder), so please have a look if you feel like it. https://scrapbox.io/yuzulia-pb/Ruby

I will update this article again when I feel like it.

Recommended Posts

Eating and comparing programming languages: Python and Ruby
Ruby, Python and map
Python and Ruby split
Programming with Python and Tkinter
Python on Ruby and angry Ruby on Python
Python and ruby slice memo
Ruby and Python syntax ~ branch ~
Solving with Ruby and Python AtCoder ABC178 D Dynamic programming
Solving with Ruby and Python AtCoder ABC011 C Dynamic programming
Solving with Ruby and Python AtCoder ABC153 E Dynamic programming
[Swift / Ruby / Python / Java] Object-oriented programming
Difference between Ruby and Python split
[Introduction to Python3 Day 1] Programming and Python
Scraping with Node, Ruby and Python
Differences between Ruby and Python in scope
Encrypt with Ruby (Rails) and decrypt with Python
Easy web scraping with Python and Ruby
Differences between Ruby and Python (basic syntax)
Python programming note
Correspondence summary of array operation of ruby and python
Instant method grammar for Python and Ruby (studying)
How to enjoy programming with Minecraft (Ruby, Python)
What is "functional programming" and "object-oriented" in Python?
Specifying the range of ruby and python arrays
What I think Python and Ruby (and languages whose types are not specified) are dung
Programming in python
What are you comparing with Python is and ==?
[Python] Learn about asynchronous programming and event loops
About shallow and deep copies of Python / Ruby
Comparison of Python and Ruby (Environment / Grammar / Literal)
Solving with Ruby, Perl, Java and Python AtCoder diverta 2019 Programming Contest C String Manipulation
AtCoder ARC080 D simulation solved in Ruby and Python
[Ruby vs Python] Benchmark comparison between Rails and Flask
Difference between Ruby and Python in terms of variables
Interprocess communication between Ruby and Python (POSIX message queue)
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
Version control of Node, Ruby and Python with anyenv
[python] Compress and decompress
Python and numpy tips
[Python] pip and wheel
Batch design and python
Python iterators and generators
3. 3. AI programming with Python
Python packages and modules
Vue-Cli and Python integration
Competitive programming diary python 20201213
Python programming with Atom
python input and output
Competitive programming diary python 20201220
Competitive programming with python
Python programming in Excel
LEGO Mindstorms 51515 Python Programming
[Python] Dynamic programming ABC015D
Python3, venv and Ansible
Python asyncio and ContextVar
Competitive programming diary python
Programming with Python Flask
Solving with Ruby and Python AtCoder ARC 059 C Least Squares
Mandelbrot Benchmark (C, PHP, HHVM, Ruby, Python, PyPy, and Kinx)
Five languages basic grammar comparison (C #, Java, Python, Ruby, Kotlin)
Compare HTTP GET / POST with cURL (command) and Python (programming)