Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 803 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create Hash iterating an array of objects

#1
I have an object that has attributes `name` and `data`, among others. I want to create a hash that uses the name as the key and the data (which is an array) as the value. I can't figure out how to reduce the code below using `map`. Is it possible?

def fc_hash
fcs = Hash.new
self.forecasts.each do |fc|
fcs[fc.name] = fc.data
end
fcs
end
Reply

#2
With Ruby 2.1 and onward, you could also use `Array#to_h`

self.forecasts.to_h { |forecast| [forecast.name, forecast.data] }
Reply

#3
I always use `inject` or `reduce` for this:

self.forecasts.reduce({}) do |h,e|
h.merge(e.name => e.data)
end
Reply

#4
Hash[*self.forecases.map{ [fc.name, fc.data]}.flatten]
Reply

#5
def fc_hash
forecasts.each_with_object({}) do |forecast, hash|
hash[forecast.name] = forecast.data
end
end
Reply

#6
Use [`Hash[]`](

[To see links please register here]

):

Forecast = Struct.new(:name, :data)
forecasts = [Forecast.new('bob', 1), Forecast.new('mary', 2)]
Hash[forecasts.map{|forecast| [forecast.name, forecast.data]}]
# => {"mary"=>2, "bob"=>1}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through