且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Ruby 中创建一个哈希来比较字符串,忽略大小写?

更新时间:2023-11-15 09:06:46

为防止此更改完全破坏程序的独立部分(例如您正在使用的其他 ruby​​ gem),请为不敏感的哈希创建一个单独的类.

To prevent this change from completely breaking independent parts of your program (such as other ruby gems you are using), make a separate class for your insensitive hash.

class HashClod < Hash
  def [](key)
    super _insensitive(key)
  end

  def []=(key, value)
    super _insensitive(key), value
  end

  # Keeping it DRY.
  protected

  def _insensitive(key)
    key.respond_to?(:upcase) ? key.upcase : key
  end
end

you_insensitive = HashClod.new

you_insensitive['clod'] = 1
puts you_insensitive['cLoD']  # => 1

you_insensitive['CLod'] = 5
puts you_insensitive['clod']  # => 5

在覆盖分配和检索功能之后,这简直是小菜一碟.创建 Hash 的完整替代品需要更加细致地处理完整实现所需的别名和其他函数(例如,#has_key? 和 #store).上面的模式可以很容易地扩展到所有这些相关的方法.

After overriding the assignment and retrieval functions, it's pretty much cake. Creating a full replacement for Hash would require being more meticulous about handling the aliases and other functions (for example, #has_key? and #store) needed for a complete implementation. The pattern above can easily be extended to all these related methods.