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 2021-09-26

Rubyでは配列末尾への追加を << で行うことができる

Ruby

sample.rb
# 配列末尾への追加
a = [1, 2]
a << 3
p a # -> [1, 2, 3]

Python

sample.py
# 配列末尾への追加
a = [1, 2]
a.append(3)
print(a) # -> [1, 2, 3]

Rubyでは多重代入の際に、変数の数と配列の要素数が異なってもエラーが起こらない

Pythonの場合、変数の数と配列の数が同じでないと、エラーが起こります。

配列の要素数が変数の数より多い場合、Rubyでは超えた分の配列の要素は無視されます。
Ruby

sample.rb
a, b = [1, 2, 3]
p(a) # -> 1
p(b) # -> 2

Python

sample.py
a, b = [1, 2, 3]  # -> ValueError: too many values to unpack (expected 2)
print(a)
print(b)

配列の要素数が変数の数より少ない場合、Rubyでは足りない分nilで埋められます。
Ruby

sample.rb
a, b = [1]
p(a) # -> 1
p(b) # -> nil

Python

sample.py
a, b = [1]  # -> ValueError: not enough values to unpack (expected 2, got 1)
print(a)
print(b)

配列のX番目からY番目を取得する方法

Rubyではlist[X...Y], list[X, 取得する要素数]で取得できます。
Pythonではlist[X:Y]です。

Ruby list[X...Y] Y番目を含まない

sample.rb
numbers = [1, 2, 3, 4, 5, 6]
print(numbers[1...4]) # > [2, 3, 4]

またlist[X..Y]ではY番目を含んで取得できます。
Ruby list[X..Y] Y番目を含む

sample.rb
numbers = [1, 2, 3, 4, 5, 6]
print(numbers[1..4]) # > [2, 3, 4, 5]

Ruby list[X, 取得する要素数]

sample.rb
numbers = [1, 2, 3, 4, 5, 6]
print(numbers[1, 3]) # > [2, 3, 4]

Python

sample.py
numbers = [1, 2, 3, 4, 5, 6]
print(numbers[1:4]) # > [2, 3, 4]
0
1
3

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?