1
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の基本(ハッシュ)

Posted at

ハッシュの定義

キーと値(バリュー)の組み合わせが重要なデータはハッシュで管理する。

sample_01.rb
# ハッシュの定義
scores = {english: 80, math: 70}
p scores
# {:english=>80, :math=>70}

# 特定のキーの値の更新
scores[:english] = 90
p scores[:english]
# 90

# データの追加
scores[:physics] = 50
scores.delete(:math)
p scores
# {:english=>90, :physics=>50}

ハッシュについて調べる

ハッシュについて調べる方法には以下のようなものがある。

sample_02.rb
scores = {english: 80, math: 70}

# 文字数
p scores.length
# 2
p scores.size
# 2

# キーや値の存在確認
p scores.has_key?(:physics)
# false
p scores.has_value?(70)
# true

# キーや値の一覧を出力
p scores.keys
# [:english, :math]
p scores.values
# [80, 70]

ハッシュをeachで処理する

eachメソッドを使ってハッシュのデータを取り出すことができる。

sample_03.rb
scores = {english: 80, math: 70}

scores.each do |subject, score|
  puts "Subject: #{subject}, Score #{score}"
end
# Subject: english, Score 80
# Subject: math, Score 70
1
0
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
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?