1
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?

【Ruby】文字列の長さを調べる方法

Posted at

文字列の長さを調べるにはlengthメソッドを使用します。

基本的な使い方

lengthメソッドは、以下のように使用します。

# 文字列の長さを取得
string = "Hello, World!"
puts string.length  # 出力: 13

空白や特殊文字もカウントされます。

string_with_spaces = " Ruby "
puts string_with_spaces.length  # 出力: 8

配列の要素を数える

配列に対してlengthメソッドを使用すると、その配列に含まれる要素の数を返します。

empty_array = []
puts empty_array.length  # 出力: 0

mixed_array = [1, "two", :three]
puts mixed_array.length  # 出力: 3

sizeメソッド

sizeメソッドもlengthメソッドと同様に使用できます。

string = "Hello"
puts string.length  # 出力: 5
puts string.size    # 出力: 5

array = [1, 2, 3]
puts array.length  # 出力: 3
puts array.size    # 出力: 3
1
1
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
1
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?