请求实现explode方法:将哈希的数组/标量转为标量组合的数组的数组
explode Hash Expansion Method I get it, sometimes problems that seem straightforward end up taking way longer than expected. Let's break down how to build this explode method to match your test cases and handle edge cases too.
Basic Implementation (Single Array Value)
First, let's tackle the core scenario from your tests—where at most one value in the hash is an array:
def explode(hash) # Separate fixed key-value pairs (non-array values) from the array-valued one fixed_entries = hash.reject { |_, val| val.is_a?(Array) }.to_a.flatten array_key, array_values = hash.find { |_, val| val.is_a?(Array) } if array_key # For each element in the array, combine with fixed entries array_values.map { |val| fixed_entries + [array_key, val] } else # No arrays? Just wrap the flattened fixed entries in an array [fixed_entries] end end
Test Case Validation
Let's plug this into your RSpec tests to confirm it works:
describe '#explode' do it 'returns a single flattened entry when no array values exist' do expect(explode({:a => 1, :b => 2})).to eq [[:a, 1, :b, 2]] end it 'expands array values into multiple full entries' do expect(explode({:a => 1, :b => [2,3,4]})).to eq [ [:a, 1, :b, 2], [:a, 1, :b, 3], [:a, 1, :b, 4] ] end end
Both tests will pass with this implementation. The first case takes all non-array entries, flattens them into a single array, and wraps it in an outer array. The second case takes the fixed :a => 1 pair, then combines it with each element from :b's array to create separate full entries.
Handling Multiple Array Values (Bonus)
If you ever need to handle hashes with multiple array-valued keys (like {:a => [1,2], :b => [3,4]}), we can adjust the method to compute the Cartesian product of all array values:
def explode(hash) # Split hash into individual entry options (single values or array elements) entry_options = hash.map do |key, val| val.is_a?(Array) ? val.map { |v| [key, v] } : [[key, val]] end # Compute all combinations and flatten each result entry_options.inject(&:product).map(&:flatten) end
For the hash {:a => [1,2], :b => [3,4]}, this returns:
[[:a, 1, :b, 3], [:a, 1, :b, 4], [:a, 2, :b, 3], [:a, 2, :b, 4]]
内容的提问来源于stack exchange,提问作者Alex Harvey

