Ruby中哈希转数组:特定嵌套哈希结构转换需求
Hey there! Let's break down how to transform your nested Ruby hash into the desired structure. Here's a straightforward approach tailored to your needs:
Step 1: Define the original hash
First, let's start with your initial nested hash:
x = { params: { user_params1: { name: "stephen", dir: "2001", dir2: nil }, user_params2: { name: "josh", dir: "jhon", dir2: nil } } }
Step 2: Apply the transformation
We'll use Ruby's built-in hash methods to convert each user parameter hash into an array, replacing nil values with empty strings. I'll cover two versions—one that handles the dir value change from "2001" to "201" as in your example, and a more generic version if that was a typo.
Version 1: With the "2001" → "201" modification
transformed_x = { params: x[:params].transform_values do |user_hash| # Extract values in order, convert nil to empty string, and adjust the dir value [ user_hash[:name], user_hash[:dir].to_s.gsub("2001", "201"), user_hash[:dir2].to_s ] end }
Version 2: Generic (no dir value modification)
If the "2001" → "201" change was a typo, use this cleaner version that simply converts all values to strings (turning nil into "" automatically):
transformed_x = { params: x[:params].transform_values do |user_hash| [user_hash[:name], user_hash[:dir], user_hash[:dir2]].map(&:to_s) end }
Step 3: Check the result
Both versions will output your desired structure. For Version 1, the result is:
{ params: { user_params1: ["stephen","201", ""], user_params2: ["josh","jhon",""] } }
Compatibility note for older Ruby versions
If you're using Ruby < 2.4 (where transform_values isn't available), use each_with_object instead:
transformed_params = x[:params].each_with_object({}) do |(key, user_hash), result| result[key] = [user_hash[:name], user_hash[:dir], user_hash[:dir2]].map(&:to_s) end transformed_x = { params: transformed_params }
内容的提问来源于stack exchange,提问作者jeff

