Dennis Ninj
Dennis Ninj

Reputation: 929

create Hash table from existing list in Ruby

I have a list with set of items such as "student ID", "Name", "Address", "score", "badge ID". How do I create a Hash Table from this existing list with a different key (preserving the original list in separate variable name)?

I have tried

new_school=Hash.new(old_school)  // ruby

but I cant find out how to assign badge_ID field as new key for the hash.

Thanks for the help, in advance

Upvotes: 1

Views: 1699

Answers (2)

Brian Underwood
Brian Underwood

Reputation: 10856

Also, note sure if you might mean taking an array of values for an object and turning them to a hash. Like this:

[123, 'Jim Bob', '123 Fake St', 90, 321]

Into this:

{:student_id => 123,
  :name => 'Jim Bob',
  :address => '123 Fake St',
  :score => 90,
  :badge_id => 321}

If so, you could do this:

keys = [:student_id, :name, :address, :score, :badge_id]
values = [123, 'Jim Bob', '123 Fake St', 90, 321]
Hash[*keys.zip(values).flatten]

Upvotes: 1

Brian Underwood
Brian Underwood

Reputation: 10856

You can use the ActiveSupport gem to turn arrays (or any other enumerable object) into a hash:

objects.index_by do |object|
  <code to calculate the hash key>
end

objects.group_by do |object|
  <code to calculate the hash key>
end

The #index_by method will make the values of the hash individual objects from the list while the #group_by method will make the values of the hash an array of the objects that map to that hash key

The code to calculate the hash key can be as simple as referencing an attribute of each object.

Upvotes: 2

Related Questions