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?

More than 1 year has passed since last update.

連想配列(Hash) の 基本的な扱い方

Last updated at Posted at 2022-09-10

目的

  • 連想配列のメリットと使い方を理解する

ポイント

  • 連想配列は、値(value)にラベル(key)をつけた 配列 のこと
  • 各要素に意味を持たせることができる
  • 要素の順序を気にする必要がない

書き方の例

#連想配列の初期化
hash = {}

#配列の場合
array = [20, 30]
#連想配列の場合
hash = {english: 20, japanese: 30}
#hash = {"english" => 20, "japanese" => 30}

p array
puts hash
puts hash[:japanese]


~実際の配列~
[20, 30]
{:english=>20, :japanese=>30}
30

注意するポイント

  • key は文字列で書くより、シンボル(コロンで指定)で書いたほうが内部的な処理がはやい
  • 文字列で配列の key を指定したら、取得する際も文字列で取得しないといけない

具体的な例

hash = Hash.new

#要素の追加
hash[:apple] = 200
p hash

#要素の更新
hash[:apple] = 300
p hash

#要素の削除
hash.delete(:apple)
p hash

~実際の表示~
{:apple=>200}
{:apple=>300}
{}

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