Comparison of Python and Ruby (Environment / Grammar / Literal)

Introduction

Hello. My name is @ sho-hata and I started working from home as soon as I joined the company. While working from home has the nice point of not having commuting time, it is difficult to switch it on and off. By the way, I've only touched Python until now, but now that I've touched Ruby on Rails at work, I spend my days studying every day. This time, since it was the first week for me to start touching Ruby, I found ["From python to Ruby"](https: // www) in the "Introduction to Ruby from Multilingual" section of ** Ruby official document **. While reading .ruby-lang.org/ja/documentation/ruby-from-other-languages/to-ruby-from-python/), I'm often worried about Ruby and python ** Similarities / Differences ** I briefly investigated and summarized. Contents will be added as appropriate. In addition, all of the following are based on Ruby.

Similarities with Python

Have an interactive execution environment

It's really convenient, isn't it? It feels like when you want to try out the code quickly, or when you want to show the true character of an interpreted language. Ruby interactive execution environment

Ruby


irb
irb(main):001:0>

Python interactive execution environment

Python


python
>>>

A little rich Python interactive execution environment

Python


ipython
In [1]:

The array (list) is a variable length array

The built-in list container is a variable length array. So, if you add elements, the number of elements will increase without permission!

Ruby


array1 = [1, 2, 3] # => [1, 2, 3]
array1[3] = 4 # => 4
array1
# => [1, 2, 3, 4]

Differences from Python

Variable string

In Python, string literals are immutable. Therefore, if they have the same value, they refer to the same address in memory.

Python


str1, str2 = "hoge", "hoge"
str1 is str2 # -> True
id(str1) # -> 140682191246064
id(str2) # -> 140682191246064

** * (4/18) postscript **

In the case of a character string, the same object is shared if it is the same string literal, but if a character string is created by an operation etc., it refers to a different memory address even if it has the same value.

Mr. @shiracamus pointed out. As shown below, when reassigning a value to a variable, it refers to a different memory address even if it has the same value. That's because a new object is created on reassignment and its reference is stored in the variable str2.

Python


str1 = "hoge"
str2 = "ho"
str2 += "ge"
str1 == str2 # -> True
str1 is str2 # -> False
id(str1) # -> 140239943766896
id(str2) # -> 140239943767152

When a variable is declared, if a string literal is concatenated by an operation to create a string, the same address in memory will be referenced if the values are the same.

Python


str1 = "hoge"
str2 = "ho" + "ge"
str1 is str2 # -> True
str1 == str2 # -> True

However, if an empty string is generated when a variable is declared and reassignment is performed, the object id of the variable after reassignment will be the same as the id of the variable with the same value. Language is difficult. .. ..

Python


str1 = "hoge"
str2 = ""
id(str1) # -> 140239943766896
id(str2) # -> 140240212059056
str2 += "hoge"
str1 is str2 # -> True
id(str2) # -> 140239943766896

However, in Ruby string literals are ** mutable **. Each points to a different memory address.

Ruby


str1, str2 = "hoge", "hoge"
p str1.equal?(str2) # => false
p str1.object_id # => 70220509475900
p str2.object_id # => 70220643515600

However, Ruby has ** symbols ** literals that are used as an alternative to string literals, which look like strings on the source and are treated internally as integers. Symbols are often used because they are immutable and consume less memory. ~~ Symbol I don't know anything ... ~~

You can create constants (variables that you don't expect their values to change)

In Ruby, identifiers that start with an uppercase alphabet are treated as constants. here, ** Constants in programming languages = Once initialized, their contents cannot be changed ** I think that is the recognition. ** But ** In Ruby it is possible to reassign to an initialized constant. (It seems that it is not recommended because it gives a warning) Therefore, no error occurs when reassigning.

Ruby


LANG = "Ruby" # => "Ruby"
LANG = "Python"
warning: already initialized constant LANG
warning: previous definition of LANG was here
# => Ruby

For me, a constant in Ruby = points to the same object id Is it the idea? It is the recognition. By the way, constants are ** not supported in Python **, but when dealing with variables (= fixed values) ** that are treated as constants, it is best to configure them with all uppercase letters and underscores (_) **. It is customary **.

Python


PREFIX = 'thank you for your hard work'
MAX_COUNT = 255

Reference: PEP 8 – Style Guide for Python Code | Python.org

No tuple

Python has an object called a tuple whose elements are immutable. It is used when you want to create a lightweight list container with fixed elements, or when you want to pack and unpack multiple elements.

Python


tuple1 = (1, 2, 3)
tuple2 = 1, 2, 3
type(tuple1) # -> <class 'tuple'>
type(tuple2) # -> <class 'tuple'>

However, Ruby does not implement tuples as built-in objects. However, it seems that tuple-like things can be done depending on the writing style.

Ruby


rb_tuple = [1, 2, 3].map(&:freeze).freeze
rb_tuple[2] = 3
# => FrozenError (can't modify frozen Array)

(Reference: Ruby engineer studied Python to diss Python)

Use elsif instead of elif

In Ruby, ** els if ** is written as a way to express ** else if **. In Python, it is written as ** elif **, but the pronunciation has changed as an abbreviation for ** else if **. Looking at what Mats, the creator of Ruby, said, it seems that the shortest number of characters and pronunciation are balanced. https://twitter.com/yukihiro_matz/status/1161556434728808448

At the end

Even with the same dynamic tidying language, Python / Ruby's unique parts were hidden in a few places. ** It is the real pleasure of studying a new language that you can think about "what kind of thought did the language designers create the language?" **! Great fun!

Recommended Posts

Comparison of Python and Ruby (Environment / Grammar / Literal)
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
Environment construction of python and opencv
Java and Python basic grammar comparison
Correspondence summary of array operation of ruby and python
Instant method grammar for Python and Ruby (studying)
Unification of Python environment
Specifying the range of ruby and python arrays
Ruby, Python and map
Python and Ruby split
python development environment -use of pyenv and virtualenv-
About shallow and deep copies of Python / Ruby
[Ruby vs Python] Benchmark comparison between Rails and Flask
Difference between Ruby and Python in terms of variables
A quick comparison of Python and node.js test libraries
Comparison table of frequently used processes of Python and Clojure
[Python] Chapter 01-02 About Python (Execution and installation of development environment)
Version control of Node, Ruby and Python with anyenv
Python on Ruby and angry Ruby on Python
Python and ruby slice memo
Python installation and basic grammar
Python environment construction and TensorFlow
Comparison of 4 Python web frameworks
Ruby and Python syntax ~ branch ~
Python 3 sorted and comparison functions
Source installation and installation of Python
Environment construction of python2 & 3 (OSX)
Python (Python 3.7.7) installation and basic grammar
Five languages basic grammar comparison (C #, Java, Python, Ruby, Kotlin)
Summary of Hash (Dictionary) operation support for Ruby and Python
Comparison of how to use higher-order functions in Python 2 and 3
Difference between Ruby and Python split
The story of Python and the story of NaN
Installation of SciPy and matplotlib (Python)
Scraping with Node, Ruby and Python
This and that of python properties
Environment construction of python3.8 on mac
Basic grammar of Python3 system (dictionary)
Speed comparison of Python XML parsing
Coexistence of Python2 and 3 with CircleCI (1.0)
Summary of Python indexes and slices
Reputation of Python books and reference books
I compared the speed of Hash with Topaz, Ruby and Python
Speed comparison of Wiktionary full text processing with F # and Python
Build and test a CI environment for multiple versions of Python
Summary of differences between Python and PHP (comparison table of main items)
[Python] Basic pattern and usage of if statement (comparison operator and Boolean operator)
Installation of Visual studio code and installation of python
Differences between Ruby and Python in scope
(Java, JavaScript, Python) Comparison of string processing
Build Python3 and OpenCV environment on Ubuntu 18.04
Python virtual environment and packages on Ubuntu
Eating and comparing programming languages: Python and Ruby
Comparison of Japanese conversion module in Python3
Python environment tool comparison chart for Rubyist
Extraction of tweet.js (json.loads and eval) (Python)
About the virtual environment of python version 3.7
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Comparison of gem, bundler and pip, venv
Connect a lot of Python or and and
python string comparison / use'list'and'in' instead of'==' and'or'