SwitchUp SwitchUp Ranked Best Coding Bootcamps 2025

Refactor following code using map in Ruby

Altcademy Team wrote on 7 February 2018

Nice how can i refactor following code using map
tag_clouds = {} tag_cloud_names.each do |name| tag_clouds[name] = row.field(row.index(name)).to_s.strip.split(",") end

You want to map an array into a hash

Hash[[[:a,:b],[:c,:d]]] (as well as Hash[:a,:b,:c,:d]) produces {:a => :b, :c => :d}.
In your case, the following should work.
tag_clouds = tag_cloud_names.map do |name| # note: I am not sure what row.field(row.index(name)).to_s.strip.split(",") is name, row.field(row.index(name)).to_s.strip.split(",") end

Update:
tag_clouds = Hash[tag_cloud_names.map do |name| # note: I am not sure what row.field(row.index(name)).to_s.strip.split(",") is name, row.field(row.index(name)).to_s.strip.split(",") end]

Trusted by

Students and instructors from world-class organizations

Join the upcoming Cohort #111

Enroll for March 2nd, 2026