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 3 years have passed since last update.

Rubyのハッシュ関連のメソッドをまとめ

Posted at

keys ハッシュのキーを配列で返す

サンプルコード

hash.rb
country_code = { japan: 'JP', australia: 'AU', canada: 'CA' }
puts "keys: #{country_code.keys}"

実行結果

keys: [:japan, :australia, :canada]

values ハッシュの値を配列で返す

サンプルコード

hash.rb
country_code = { japan: 'JP', australia: 'AU', canada: 'CA' }
puts "values: #{country_code.values}"

実行結果

values: ["JP", "AU", "CA"]

has_key?, key?, include?, member?

サンプルコード

hash.rb
country_code = { japan: 'JP', australia: 'AU', canada: 'CA' }
puts country_code.has_key?(:japan)
puts country_code.has_key?(:ua)

実行結果

true
false

merge 2つのハッシュを結合する

サンプルコード

hash.rb
country_code_asia = { japan: 'JP' }
country_code_oceania = { australia: 'AU' }
country_code_asia_oceania = country_code_asia.merge(country_code_oceania)
puts "country_code_asia: #{country_code_asia}"
puts "country_code_asia_oceania: #{country_code_asia_oceania}"

実行結果

country_code_asia: {:japan=>"JP"}
country_code_asia_oceania: {:japan=>"JP", :australia=>"AU"}

**でハッシュを展開することも可能

サンプルコード

hash.rb
country_code_asia_oceania_asta = { **country_code_asia, **country_code_asia_oceania}
puts "country_code_asia_oceania_asta: #{country_code_asia_oceania_asta}"

実行結果

country_code_asia_oceania_asta: {:japan=>"JP", :australia=>"AU"}

**で他のキーワード引数を受け取ることができる

サンプルコード

hash.rb
def order_subwey(main, bread, cheese: false, tsuna: false, **other_topping)
    puts "main: #{main}"
    puts "bread: #{main}"
    if cheese
        puts "cheese"
    end
    if tsuna
        puts "tsuna"
    end
    puts "other_topping #{other_topping}"
end
order_subwey("BLT", "Sesame", cheese: true, tsuna: true, bacon: true, avocado: true)

実行結果

main: BLT
bread: BLT
cheese
tsuna
other_topping {:bacon=>true, :avocado=>true}
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?