基于指定YAML格式验证Ruby提交哈希的有效性
Got it, let's walk through how to solve this problem—you need to validate a Ruby hash against parameter dependency rules defined in YAML, plus parse that YAML into a usable Ruby structure first. Here's a clear, step-by-step solution:
First, let's formalize your YAML rule set (I've cleaned up the formatting for clarity):
parameters: - param_name: age requires: - name - param_name: height requires: - name
To turn this into a Ruby object we can work with, use YAML.safe_load (safer than plain load to avoid execution risks):
require 'yaml' # You can also load this from a file with YAML.safe_load(File.read('rules.yml')) yaml_rules = <<~YAML parameters: - param_name: age requires: - name - param_name: height requires: - name YAML # Parse into an array of rule hashes parameter_rules = YAML.safe_load(yaml_rules)['parameters'] # Result: [{"param_name"=>"age", "requires"=>["name"]}, {"param_name"=>"height", "requires"=>["name"]}]
The core logic here is: if a submission includes a parameter from the rules, it must include all of that parameter's required dependencies. We'll also handle a common Ruby gotcha: mixing symbol and string hash keys by normalizing everything to strings.
Here's the validation method:
def valid_submission?(submission_hash, parameter_rules) # Normalize submitted keys to strings to avoid symbol/string mismatches submitted_keys = submission_hash.keys.map(&:to_s) parameter_rules.each do |rule| current_param = rule['param_name'] # Only check dependencies if the parameter is present in the submission next unless submitted_keys.include?(current_param) required_params = rule['requires'] # Find any required parameters that are missing from the submission missing_params = required_params - submitted_keys unless missing_params.empty? puts "❌ Invalid: Parameter '#{current_param}' requires missing fields: #{missing_params.join(', ')}" return false end end # All checks passed puts "✅ Submission is valid!" true end
Let's run through the test cases you mentioned:
# Test 1: Invalid submission (missing 'name') invalid_submission = { age: 15, height: '6ft' } valid_submission?(invalid_submission, parameter_rules) # Output: ❌ Invalid: Parameter 'age' requires missing fields: name # Returns: false # Test 2: Valid submission (includes all required fields) valid_submission = { age: 15, name: '张三', height: '6ft' } valid_submission?(valid_submission, parameter_rules) # Output: ✅ Submission is valid! # Returns: true
- If a submission doesn't include a parameter (e.g., only
{name: '张三'}), it's automatically valid—we only validate dependencies when the parameter is present. - If you need to enforce that certain parameters must be present (not just their dependencies), you can add an extra check for required base parameters.
内容的提问来源于stack exchange,提问作者jacksonecac

