LoginSignup
4
1

More than 5 years have passed since last update.

Rubyのhashに関する処理あれこれ

Posted at

よく忘れるので。

  • keyとvalueをstringからintegerにしたい
hash = { '1' => '2', '3' => '4' }
Hash[*(hash.to_a.flatten.map(&:to_i))]
  • ActiveRecord_Relation{ id: somthing, id: something }みたいにしたい。
users = User.limit(10)
Hash[*users.map { |u| [u.id, u.point] }.flatten]
  • hash間の差分を出したい
hash_a = { 1 => 2, 3 => 5, 4 => 6 }
hash_b = { 1 => 2, 3 => 4 }
diff = (hash_a.to_a - hash_b.to_a).to_h
4
1
1

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
4
1