简体   繁体   中英

Combine 3 arrays into Hash in Ruby on Rails

I have 3 arrays: min , max and regions . I want to create a hash for each region with corresponding min and max value. Something like this:

regions=["Region 1","Region 2",....]
min=["100","200",...]
max=["500","300",...]

#=> {"Region1"=>["100", "500"], "Region 2"=>["200", "300"], ...}

Here is my code:

@min = params[:min]
@max = params[:max]
@regions = params[:regions]

I have tried this so far, but didn't work:

@range_map = Hash[@regions.map{|r| [r, [@min.each.to_i,@max.each.to_i]]}]

All I want is a hash from 3 array and min and max to be converted to integer .

You can try something like this, using zip and transpose :

range_map = regions.zip([min.map(&:to_i), max.map(&:to_i)].transpose).to_h

#=> {"Region1"=>[100, 500], "Region2"=>[200, 300]}

Demonstration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM