GreenTriangle
GreenTriangle

Reputation: 2460

Turning an array into a hash's keys, with a specified value for all items?

Basically, I want to create the hash {1959: 0, 1960: 0, 1961: 0, 1962: 0} and so on without manually writing it out.

I figure I start with [*1959..2014] but don't know where to go from there.

Upvotes: 0

Views: 49

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

One way:

Hash[[*1959..2014].product([0])]

Upvotes: 1

philnash
philnash

Reputation: 73029

You can use inject with your array to form the hash, like so:

(1959..2014).inject({}) { |hash, year| hash[year] = 0; hash }

inject is like each in that in runs over each member of an enumerable, but it passes 2 arguments to the block, the current object and an object that you can use to collect the results, in this case a hash.

Or, as @sawa points out in the comment below:

(1959..2014).each_with_object({}) { |year, hash| hash[year] = 0 }

each_with_object doesn't require you to return the object at the end of the block like inject does.

[edit] Just used the plain range, rather than an array. Added each_with_object option.

Upvotes: 1

falsetru
falsetru

Reputation: 369064

You can use Hash::[]:

Hash[(1959..1962).map { |x| [x, 0] }]
# => {1959=>0, 1960=>0, 1961=>0, 1962=>0}

or Enumerable#to_h in Ruby 2.1+:

(1959..1962).map { |x| [x, 0] }.to_h
# => {1959=>0, 1960=>0, 1961=>0, 1962=>0}

(changed the ending year for brevity of outputs)

Upvotes: 1

Related Questions