0
0

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)

Last updated at Posted at 2025-05-21

基本的なメソッド(Ruby)

Rubyには配列や数値、ハッシュを扱うための便利なメソッドが多数あります。今回はよく使う基本的なものをまとめてみました。

配列

array[index]

指定したindexで要素を取得する。負の数で末尾からも指定可能です。

array = ['water', 'tea', 'coffee']
puts array[1]   # => "tea"
puts array[-1]  # => "coffee"

array.first

配列の最初の要素を取得する。

array = ['water', 'tea', 'coffee']
puts array.first # => "water"

array.last

配列の最後の要素を取得する。

array = ['water', 'tea', 'coffee']
puts array.last # => "coffee"

array.join

配列の要素を結合して一つの文字列にする。

array = ['water', 'tea', 'coffee']
puts array.join("-") # => "water-tea-coffee"

array.map

各要素に処理をして、新しい配列として返します。
元の配列は変更されない

array = ['water', 'tea', 'coffee']
new_array = []
new_array = array.map{|data|   data + "です" } # ですを追加
puts new_array # => ["waterです", "teaです", "coffeeです"]

array.each

各要素に対して処理を実行します。返り値は元の配列です。
元の配列は変更されません
副作用が主な仕様目的(表示、 保存など)

array = ['water', 'tea', 'coffee']
new_array = []
new_array = array.each{|data| puts data } # 配列の中身を表示

array.sort

昇順に並べ替えます。

array = [9, 2, 5, 8, 2]
puts array.sort # => [2, 2, 5, 8, 9]

array.reverse

配列の要素の並びを逆にする。

array = [9, 2, 5, 8, 2]
puts array.reverse # => [2, 8, 5, 2, 9]

array.include?

値が含まれているか確認する。
返り値はboolean型

array = [9, 2, 5, 8, 2]
puts array.include?(6) # => false

array.uniq

重複を取り除きます。

array = [9, 2, 5, 8, 2]
puts array.uniq # => [9, 2, 5, 8]

array.max

配列から最大値を出力する。

array = [9, 2, 5, 8, 2]
puts array.max # => 9

array.min

配列の最小値を出力する。

array = [9, 2, 5, 8, 2]
puts array.min # => 2

array.sum

配列の要素の合計を求める。

array = [9, 2, 5, 8, 2]
puts array.sum # => 26

数字

number.to_i

int型に変換

number = '12'
puts number.to_i + 18 # => 30

number.to_f

froot型に変換

number = '12'
puts number.to_f # => 12.0

number.ceil

小数点を切り上げ

number = 12.1
puts number.ceil # => 13

number.floor

小数点を切り捨て

number = '12.1'
puts number.to_i # => 12

number.round

四捨五入をする

number = '12.5'
puts number.round # => 16

ハッシュ

Hashはキー(key)と値(value)の組み合わせを管理するデータ構造

hash.key?(key) / hash.has_key?(key)

指定のキーが有るか確認する。

hash = { "apple" => 100, "banana" => 200 }

この例では:

  • "apple" がキー、100 が値
  • "banana" がキー、200 が値
hash = { 1 => "water", 2 => "tea" }
puts hash.key?("water") # => false(キーの存在確認)
puts hash.has_value?("water") # => true(値の存在確認)

まとめ

他にも様々あるので、調べて活用していきたい。

0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?