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?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-01-26

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