0
2

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 1 year has passed since last update.

RubyとPythonの基本的な書き方の差まとめ

Last updated at Posted at 2023-06-27

言語が変わると書き方もちょっと変わる。RubyとPythonのよく使う基本的な書き方について、違いをまとめて見ました。

文字列の出力

Python

print("Hellow World")

Ruby

puts "Hello World"

ターミナルでの入力を受け取る

Python

x = input("入力してください")

Ruby

puts "入力してください"
x = gets

変数の型変換(文字列から整数)

Python

string_x = "1"
integer_x = int(string_x)

Ruby

string_x = "1"
integer_x = string_x.to_i

変数展開

Python

name = "Suzuki"
age = 18
# 書き方1
print(f'私の名前は{name}です。年齢は{age}歳です')
# 書き方2
print('私の名前は{}です。年齢は{}歳です'.format(name, age))

Ruby

name = "Suzuki"
age = 18
puts "私の名前は#{name}です。年齢は#{age}歳です"

条件分岐

Python

x = int(input())
if x % 15 == 0:
    print(f'{x}は15の倍数です')
elif x % 3 == 0:
    print(f'{x}は3の倍数です')
elif x % 5 == 0:
    print(f'{x}は5の倍数です')
else:
    print(f'{x}は3の倍数でも5の倍数でもないです')

Ruby

x = gets.to_i
if x % 15 == 0 #thenは省略
    puts "#{x}は15の倍数です"
elsif x % 3 == 0
    puts "#{x}は3の倍数です"
elsif x % 5 == 0
    puts "#{x}は5の倍数です"
else
    puts "#{x}は3の倍数でも5の倍数でもないです"
end

繰り返し処理

Python

for i in range(100):
    print(i)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
    print(number)

Ruby

100.times do |i|
    puts i
end
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers.each do |number|
    puts number
end

論理演算子(かつ、または、否定)

Python

# a > 0 かつ b > 0
a > 0 and b > 0

# a > 0 または b > 0
a > 0 or b > 0

# a > 0 ではない
not a > 0

Ruby

# a > 0 かつ b > 0
a > 0 && b > 0

# a > 0 または b > 0
a > 0 || b > 0

# a > 0 ではない
!(a > 0)
0
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?