Last active
May 24, 2017 11:12
-
-
Save Peranikov/585a73e91c768874ec982d1f8a8a72e6 to your computer and use it in GitHub Desktop.
Hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Hash | |
array = [1, 2] | |
# Hashのキーには通常、Object#hashの値が使われる | |
# ミュータブルなオブジェクトはHashのキーに向かない | |
array.hash # => -2511718100518778594 | |
array.reverse! # => [2, 1] | |
array.hash # => -206156502938470765 | |
# Stringもミュータブルだが、利便性のために例外扱いとなっている | |
# 繰り返し処理 | |
hash = {one: 1, two: 2} | |
# キーと値を繰り返す | |
hash.each do |key, val| | |
puts "#{key}: #{val}" | |
end | |
# キーだけを繰り返す | |
hash.each_key do |key| | |
puts "#{key}" | |
end | |
# 値だけを繰り返す | |
hash.each_value do |val| | |
puts "#{val}" | |
end | |
# 値の更新/追加/削除 | |
# 追加 | |
hash = {} | |
hash[:foo] = 'bar' | |
hash # => { :foo => "bar" } | |
# 削除 | |
hash.delete(:foo) # => "bar" | |
hash # => {} | |
hash = {foo: 1, bar: 2, baz: 3} | |
# 値の整数が奇数であれば残す | |
hash.select! {|key, val| val.odd?} | |
hash # => {:foo=>1, :baz=>3} | |
# 値の整数が奇数であれば取り除く | |
hash.reject! {|key, val| val.odd?} | |
hash # => {:bar=>2} | |
# keep_if,delete_ifで常にselfを返せる | |
hash = {foo: 1, bar: 2, baz: 3} | |
# 変更が無くても常にselfを返す | |
hash.keep_if {|key, val| true } # => {:foo=>1, :bar=>2, :baz=>3} | |
hash.delete_if {|key, val| false } # => {:foo=>1, :bar=>2, :baz=>3} | |
# 非破壊的メソッド | |
hash = {foo: 1, bar: 2, baz: 3} | |
hash.select {|key, val| val.odd?} # => {:foo => 1, :baz => 3} | |
hash.reject {|key, val| val.odd?} # => {:bar => 2} | |
# Ruby 2.4から追加されたメソッド | |
# Hash#transform_values | |
names = {a: 'alice', b: 'bob', c: 'chalie'} | |
names.transform_values {|name| name.capitalize} # => {a: 'Alice', b: 'Bob', c: 'Chalie'} | |
# Hash#compact | |
hash = {a: 1, b: nil} | |
hash.compact # => {:a => 1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment