LoginSignup
0
0

More than 5 years have passed since last update.

[Ruby] Array から Hash を生成

Last updated at Posted at 2019-03-10

概要

このコードの動作は?

array = []
n.times do
  array << [:a, :b].zip(gets.split().map(&:to_i)).to_h
end
array
  # => [{:a=>1, :b=>2}, {:a=>3, :b=>4}]

動作

# zip でまとめる
a = [:a, :b].zip([1, 2])
  # => [[:a, 1], [:b, 2]]

# Hash に変換
h = a.to_h
  # => {:a=>1, :b=>2}

サンプル

array = [1, 2]
[:p, :b].zip(array).to_h
  # => {:p=>1, :b=2}
array = [1, 2, 3].map { |id| User.new(id) }
array.map(&:id).zip(array).to_h
  => {1=>#<User:0x00007fc97da12950 @id=1>, 2=>#<User:0x00007fc97da12928 @id=2>, 3=>#<User:0x00007fc97da12900 @id=3>}

class User
  attr_accessor :id
  def initialize(id)
    @id = id
  end
end

資料

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