0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RubyとPythonの構文比較まとめ

Last updated at Posted at 2020-11-30

はじめに

ひとつのプログラミング言語を学ぶと、他のプログラミング言語にも応用できると言われています。
そこで、言語の壁を超えて、基本的な構文を比較しながらまとめてみました。

投稿者のスキルセット

・RailsでWebアプリケーションを作成したことがある
・ProgateやRailsチュートリアルで、Rubyを学んだ経験がある
・ProgateでPythonを学習中

対象者

・Rubyを学んでいて、Pythonに興味を持っている方
・逆にPythonを学んでいて、Rubyにも興味を持っている方

環境

・MacOS Catalina 10.15.7
・Ruby 2.7.1
・Python 3.8.6

構文

「Hello, World!」を出力する

hello.rb
puts 'Hello,world!'
hello.py
print('Hello, World!')

putsとprintで言語の違いがありますが、おおむね同じですね。

コメント

comment.rb
# これはコメントです
comment.py
# これはコメントです

コメントの付けかたは、『#』で変わりません。

条件文

if.rb
def check(number)
    if number % 4 == 0
        puts('number is divisible by 4')
    elsif number % 3 == 0
        puts('number is divisible by 3')
    elsif number % 2 == 0
        puts('number is divisible by 2')
    else
        puts('number is not divisible by 4, 3, or 2')
    end
end
if.py
def check(number):
    if number % 4 == 0:
        print('number is divisible by 4')
    elif number % 3 == 0:
        print('number is divisible by 3')
    elif number % 2 == 0:
        print('number is divisible by 2')
    else:
        print('number is not divisible by 4, 3, or 2')

Rubyでは『elsif』ですが、Pythonでは『elif』なところに注意が必要です。
また、Pythonでは条件文の末尾に:が必要ですが、Rubyでは不要です。

おわりに

今回は、分かりやすい一例をご紹介しました。
基本的には、一つの言語を学べば、他の言語にも活かせると言えそうです。
まずは基礎となる言語の理解をしっかりと深めるところから始めましょう!

参考

・ゼロから学ぶ Python
https://rinatz.github.io/python-book/

0
1
10

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?