Skip to content

Instantly share code, notes, and snippets.

@denisoster
Last active April 24, 2020 08:08
Show Gist options
  • Save denisoster/f61dcbdb20acc6cd8af1afa1c3714ac9 to your computer and use it in GitHub Desktop.
Save denisoster/f61dcbdb20acc6cd8af1afa1c3714ac9 to your computer and use it in GitHub Desktop.
>> attributes_keys
{:country_ids=>:country_id, :group_type_ids=>:group_type_id, :region_ids=>:region_id, :city_ids=>:city_id}
(byebug) >> keys
[:country_ids, :city_ids]
(byebug) >> attributes_keys.slice(*keys)
{:country_ids=>:country_id, :city_ids=>:city_id}
(byebug) >> attributes_keys.slice(*keys).values
[:country_id, :city_id]
(byebug) >> attributes_keys.slice(*keys).values.zip(p)
[[:country_id, 1001], [:city_id, 1213]]
(byebug) >> Hash[attributes_keys.slice(*keys).values.zip(p)]
{:country_id=>1001, :city_id=>1213}
(byebug)
attributes = {
:country_ids => [1001],
:group_type_ids => [],
:city_ids => [1213, 1214],
:region_ids => []
}.delete_if { |_k, v| v.blank? }
attributes_keys = {
country_ids: :country_id,
group_type_ids: :group_type_id,
region_ids: :region_id,
city_ids: :city_id
}
keys = attributes.keys
attrs = keys.map { |key| attributes[key] }
product = attrs[0].product(*attrs[1..-1])
product.map do |p|
Hash[attributes_keys.slice(*keys).values.zip(p)]
end
# => [{:country_id=>1001, :city_id=>1213}, {:country_id=>1001, :city_id=>1214}]
@senid231
Copy link

senid231 commented Apr 24, 2020

# country_ids, group_type_ids, region_ids, city_ids are always arrays with zero or more elements
countries_ids = country_ids.empty? ? [nil] : country_ids
group_types_ids = group_type_ids.empty? ? [nil] : group_type_ids
regions_ids = region_ids.empty? ? [nil] : region_ids
cities_ids = city_ids.empty? ? [nil] : city_ids
# country_ids = [1,2]; group_type_ids = [3,4]; region_ids = []; city_ids = [];
# => [[1, 3, nil, nil], [1, 4, nil, nil], [2, 3, nil, nil], [2, 4, nil, nil]]
values_list = countries_ids.product(group_types_ids, regions_ids, cities_ids)
keys = [:country_id, :group_type_id, :region_id, :city_id]
values_list.map { |values| Hash[keys.zip(values)] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment