如何在 Ruby 中创建一个哈希来比较字符串,忽略大小写? [英] How do I create a hash in Ruby that compares strings, ignoring case?

查看:14
本文介绍了如何在 Ruby 中创建一个哈希来比较字符串,忽略大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,我想将一些内容存储在 Hash 中,但我不希望它区分大小写.例如:

In Ruby, I want to store some stuff in a Hash, but I don't want it to be case-sensitive. So for example:

h = Hash.new
h["HELLO"] = 7
puts h["hello"]

这应该输出 7,即使情况不同.我可以覆盖散列的相等方法或类似的方法吗?

This should output 7, even though the case is different. Can I just override the equality method of the hash or something similar?

谢谢.

推荐答案

为防止此更改完全破坏程序的独立部分(例如您正在使用的其他 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.

这篇关于如何在 Ruby 中创建一个哈希来比较字符串,忽略大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆