Convert Array to Hash in Ruby Code Example

Last Updated On Friday 10th Jun 2022

Ruby’s Collect method

  • Ruby’s collect method is part of the Enumerable mixin.
  • A mixin which provides very useful and powerful methods for collection objects.
  • It allows you to transform each element of your collection object into something else.
	hash = Hash[array.collect { |item| [item, ""] } ]
	

Let’s see the small example with the collect method.

	[1, 2, 3].collect{ |num| num * 4 }
	

array to hash ruby

Example 1

	names = %w(adam alice benny matt)
hash = Hash[names.collect { |item| [item, item.capitalize()] } ]
	

Output

	# {"adam"=>"Adam", "alice"=>"Alice", "benny"=>"Benny", "matt"=>"Matt"}
	

Example 2 ruby hash.map

	arr = [1, 2, 3]
Hash[arr.map{|n| [n, n*5]}]
	

Output

	# {1=>5, 2=>10, 3=>15}
	

Array vs Hashes

  • Arrays are the way to Store values sequentially.
	arr = ["California", "London", "Washington", "Paris"]
	
  • Reference values by key
  • Hashes are the way to store values by name (key).
	domains = {
  "de" => "Germany",
  "es" => "Spanish",
  "us" => "United States",
  "no" => "Norway"
}
	
  • Reference values by key
  • Anything can be the key to a hash like Strings, symbols, Integers, Floats, even other arrays or hashes.
convert array to hash ruby
ruby convert array to hash
rails convert array to hash
convert array to hash
convert hash to array ruby
ruby array to hash
array to hash ruby
ruby hash map
convert array into hash ruby
array to hash