You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby哈希中如何让用户输入匹配字符串键(忽略格式差异)

解决方案

核心思路是统一输入与哈希键的匹配规则,消除大小写、空格差异带来的匹配问题,具体实现如下:

1. 编写标题标准化函数

这个函数会将任意格式的标题(输入字符串、哈希中的字符串/符号键)转换成统一格式,消除格式差异:

def normalize_title(title)
  # 先把输入转为字符串,兼容符号键的处理
  title_str = title.to_s
  # 标准化规则:转小写、去首尾空格、合并连续空格
  title_str.downcase.strip.gsub(/\s+/, ' ')
end

2. 修改add分支的判断逻辑

不再直接通过键名索引哈希,而是遍历所有键,用标准化后的结果做匹配:

case choice
when "add"
  puts "What movie would you like to add? "
  input_title = gets.chomp
  normalized_input = normalize_title(input_title)
  
  # 遍历哈希查找匹配的电影
  existing_movie = movies.find do |key, _rating|
    normalize_title(key) == normalized_input
  end

  if existing_movie.nil?
    puts "What rating does the movie have? "
    rating = gets.chomp
    # 推荐存为字符串,避免带空格的标题转符号出现下划线的问题
    movies[input_title] = rating.to_f
  else
    _, rating = existing_movie
    puts "That movie already exists! Its rating is #{rating}."
  end
end

关键细节说明

  • 兼容两种键类型:不管哈希里的键是字符串(如"Lord of the Rings")还是符号(如:Inception),标准化函数都能将其转为统一格式,和用户输入的标准化结果对比。
  • 处理空格差异:用户输入"lord of the rings"会被标准化为"lord of the rings",能匹配哈希里的"Lord of the Rings"。
  • 大小写不敏感:用户输入"HURT locker"或"hurt LOCKER",标准化后都是"hurt locker",可匹配哈希中的"Hurt Locker"。

完整修改后的代码

def normalize_title(title)
  title_str = title.to_s
  title_str.downcase.strip.gsub(/\s+/, ' ')
end

movies = {
  "Lord of the Rings" => 4,
  Inception: 4, 
  "Hurt Locker" => 3.5,
  Mother: 4
}

puts "What would you like to do?"
puts "-- Type 'add' to add a movie."
puts "-- Type 'update' to update a movie."
puts "-- Type 'display' to display a movie."
puts "-- Type 'delete' to delete a movie."

choice = gets.chomp

case choice
when "add"
  puts "What movie would you like to add? "
  input_title = gets.chomp
  normalized_input = normalize_title(input_title)
  
  existing_movie = movies.find do |key, _rating|
    normalize_title(key) == normalized_input
  end

  if existing_movie.nil?
    puts "What rating does the movie have? "
    rating = gets.chomp
    movies[input_title] = rating.to_f
  else
    _, rating = existing_movie
    puts "That movie already exists! Its rating is #{rating}."
  end
end

内容的提问来源于stack exchange,提问作者Stepdeff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:54:22