Skip to content

Instantly share code, notes, and snippets.

@Peranikov
Last active June 28, 2017 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Peranikov/09e3bd15d4984f6d5d3c365e728239ef to your computer and use it in GitHub Desktop.
Save Peranikov/09e3bd15d4984f6d5d3c365e728239ef to your computer and use it in GitHub Desktop.
5-5-3 Hash マージ
# マージ
a = { one: 'A', two: nil }
b = { two: 'B', three: 'C' }
a.merge(b) # => {:one=>"A", :two=>"B", :three=>"C"}
# mergeは疑似キーワード引数にデフォルト値をもたせたいときに便利
def keywords(hash = {})
defaults = {alice: 'ありす', bob: 'ぼぶ'} # デフォルト値のハッシュ
hash = defaults.merge(hash)
hash
end
keywords bob: 'ボブ' # => {alice: 'ありす', bob: 'ボブ'}
# 破壊的メソッド
hash = {one: 'A'}
hash.merge! two: 'B' # => {one: 'A', two: 'B'}
hash # => {one: 'A', two: 'B'}
# キーと値の入れ替え
{one: 1, two: 2}.invert # => {1 => :one, 2 => two}
{foo: 1, bar: 1}.invert # => {1 => :bar} おなじ要素なので片方が消える。どちらが残るかは不定
# キーや値が存在しているか
hash = {foo: nil}
# 値がnilだとキーがあるのか判別できない
hash[:unknown] # => nil
hash[:foo] # => nil
# キーが存在するかを判定する
hash.has_key?(:unknown) # => false
hash.has_key?(:foo) # => true
# これらはhas_key?と同じ
hash.key?(:foo) # => true
hash.member?(:foo) # => true
hash.include?(:foo) # => true
# ぼっち演算子での安全な値の取り方
hash = {bar: "buzz"}
hash&.[](:bar) # => "buzz"
hash = nil
hash&.[](:bar) # => nil
# 値が存在するか
hash = {foo: 'bar'}
hash.has_value?("bar") # => true
hash.has_value?("baz") # => false
# has_value?と同じ
hash.value?("bar") # => true
# キーの取得
h = {one: 'A', two: 'B', three: 'C'}
h.keys # => [:one, :two, :three]
# 値に対応したキーを取得する
h = {one: 'A', two: 'B', three: 'C'}
h.key('B') # => :two 値が複数ある場合は不定
# 値の取得
h = {one: 'A', two: 'B', three: 'C'}
h.values # => ["A", "B", "C"]
# 特定の値のみ取得したい場合
h.values_at(:three, :two) # => ["C", "B"]
# 深い階層のエラーを取得する
hash = {
allice: {
books {
wonder: 1865
}
},
charlie: {}
}
hash[:alice][:books][:wonder] # => 1865
hash.dig(:alice, :books, :wonder) # => 1865
hash[:charlie][:books][:chocolate] # => #digを使わないとNoMethodErrorになる
hash.dig(:charlie, :books, :chocolate) # => nil
# digメソッドを持つオブジェクト(ここでいうArray)であれば、digで深い階層の値を取得することができる
hash = {a: [{word: 'alice'}, {word: 'alpha'}]}
hash.dig(:a, 0, :word)
# デフォルト値を指定する
has_default = Hash.new("undefined")
has_default['foo'] # => "undefined"
# デフォルト値は同一オブジェクトなので、破壊的変更を受ける
has_default = Hash.new("naive")
value = has_default['foo']
value.reverse!
has_default['foo'] # => "evian"
# デフォルト値
has_default = {}
has_default['foo'] # => nil
has_default.default = 'bar' # デフォルト値を設定
has_default['foo'] # => "bar"
# ブロックで指定できる
has_default.default_proc = ->(hash, key) {Time.now}
has_default['foo'] # => 2017-06-28 20:17:26 +0900
hash = {}
hash.fetch('foo', 'default') # => "default"
hash.fetch('foo') {|key| key} # => "foo"
hash.fetch('foo') # KeyError: key not found: "foo"
# ハッシュをArrayに変換
a = {one: 1, two: 2}.to_a # => [[:one, 1], [:two, 2]]
a.assoc(:one) # => [:one, 1] 2次元配列
# Arrayをハッシュに変換
ary = ["key1", "one", "key2", "two"]
Hash[*ary] # => {"key1"=>"one", "key2"=>"two"}
# 2次元配列からハッシュに変換
ary = [["key1", "one"], ["key2", "two"]]
Hash[ary] # => {"key1"=>"one", "key2"=>"two"}
ary.to_h # => {"key1"=>"one", "key2"=>"two"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment