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

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

问题描述

在Ruby中,我想将一些东西存储在哈希中,但我不希望它是区分大小写的。例如:

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

即使情况不同,这应该输出7。我可以重写散列的相等方法或类似的东西吗?



谢谢。

解决方案<为了防止这种改变从完全破坏你的程序的独立部分(比如你正在使用的其他ruby宝石),为你的不敏感散列创建一个单独的类。

  class HashClod< Hash 
def [](key)
super_insensitive(key)
end
$ b def [] =(key,value)
super _insensitive(key ),值
结束

#保持干燥。
保护

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

you_insensitive = HashClod.new

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

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

在覆盖赋值和检索函数之后,它几乎是蛋糕。创建哈希的完整替换需要更加细致地处理完整实现所需的别名和其他函数(例如#has_key?和#store)。上面的模式很容易扩展到所有这些相关的方法。


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"]

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

Thanks.

解决方案

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

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天全站免登陆