Ruby实现AWS API要求的数组首元素存逗号分隔字符串问题
Hey there! I get it—you're a sysops pro, not a full-time dev, and you need that specific tag format for the AWS API where the tag value is a single comma-separated string inside an array (like ["stage,qa,dev"] instead of ["stage","qa","dev"]). Let's fix that multi_value method right up.
The Problem with Your Current Code
Your existing Validate.multi_value method is splitting the input into multiple array elements whenever it sees spaces or commas, which is exactly what you don't want. Instead, we need to replace any spaces (or mixed separators) with commas and keep the whole thing as one string inside the array.
The Corrected Solution
Update your Validate class's multi_value method to this:
class Validate def self.multi_value(value) # Grab the raw input string from the input array input = value.first # Replace any combination of spaces, commas, or dots with a single comma formatted_value = input.gsub(/[,.\s]+/, ',') # Return the formatted string wrapped in an array (just like AWS expects) [formatted_value] end end
How This Works
Let's walk through your example input:
- If you enter
stage dev qa, the method will replace the spaces with commas, resulting in"stage,dev,qa", then wrap it in an array:["stage,dev,qa"] - If you enter
stage,qa,dev(already commas), it stays as"stage,qa,dev"in the array - If you enter something messy like
prod, staging dev, it cleans it up to"prod,staging,dev"in the array - Even a single value like
prodwill just return["prod"], which is valid too
Quick Note on Your set_values Method
You can keep your Tags#set_values method mostly as-is, but just a tiny tweak: gets.strip.chomp is redundant because strip already removes leading/trailing whitespace (including newlines from gets). You can simplify that line to:
@tags[key] = [gets.strip]
That's it! Now your tags will be formatted exactly how the AWS API needs them.
内容的提问来源于stack exchange,提问作者ikRubyTuesday

