Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

[Ruby]Hashクラスのメソッド

1年くらい前にRubyの勉強のためにHashクラスの便利メソッドをまとめたもの

参考
パーフェクトRuby
https://docs.ruby-lang.org/ja/latest/class/Hash.html

繰り返し

each_key
ハッシュのキーだけを繰り返す

each_value
ハッシュの値だけを繰り返す

hash = { ruby: 1, java: 2}

hash.each_key{ |key| puts key} # => "ruby" "java" と順番に出力
hash.each_value{ |val| puts val} # => "1" "2" と順番に出力

マージ

2つのハッシュを1つにまとめる

a = { ruby: 1, java: 2}
b = { php: 3, ruby: 5}

a.merge(b) # => {:ruby=>5, :java=>2, :php=>3}

キーと値の入れ替え

invert
キーと値を入れ替えた新しいハッシュを生成

hash = { ruby: 1, java: 2}
hash.invert # => {1=>:ruby, 2=>:java}

キーや値の確認

has_key?
指定したキーが存在するか確認(値がnilか区別を付けるため)

hash = {hoge: nil}

hash[:unknown]   # => nil
hash[:hoge]  # => nil

hash.has_key?(:unknown) # => false
hash.has_key?(:hoge)        # => true

has_value?
指定した値を持つエントリが存在するか確認

hash = {ruby: 1}

hash.has_value?(1) # => true
hash.has_value?(2) # => false

デフォルト値の設定

Hah.newの第一引数にデフォルト値を指定できる

hash = Hash.new('ruby')
hash[:a] # => "ruby"

hash = Hash.new { |v| 'java'}
hash[:b] # => "java"

fetch
指定したキーに値が存在しない場合の戻り値を指定

hash = {ruby: 1}

hash.fetch(:ruby, 5) # => 1
hash.fetch(:java, 5) # => 5
hash.fetch(:java) {|key| key} # => :java
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
0
Help us understand the problem. What are the problem?