首页 > 解决方案 > 将 Ruby 哈希转换并转换为人类可读的字符串

问题描述

标签: rubystringhash

解决方案


I'd suggest using hashes for mapping out the possible values, e.g.:

days_ago_filter_map = {
  "lt" => "Less than",
  # ...other cases here...
}

musical_key_map = {
  3 => "D♯, E♭",
  # ...other cases here...
}

Then you can switch on the key:

variables.map do |key, value| 
  label = "#{key.split('_').map(&:capitalize).join(' ')}"
  formatted_value = case key
  when "days_ago_filter" then days_ago_filter_map.fetch(value)
  when "key" then musical_key_map.fetch(value)
  else value
  end
  "#{label}: #{formatted_value}" 
end.join(' - ')

Note that if you're missing anything in your maps, the above code will raise KeyNotFound errors. You can set a default in your fetch, e.g.

days_ago_filter_map.fetch(value, "Unknown filter")
musical_key_map.fetch(value, "No notes found for that key")

推荐阅读