修改字符串类以仅使用大写

时间:2017-11-08 17:34:11

标签: ruby

我有一个处理一些基本数据的小应用程序(名称,生日等)。它将与仅接受大写字符串的管理系统连接。想办法解决这个问题,我知道我可以使用.upcase来处理所有变量。我认为最干的方法是修改String类本身并进行转换,但是找不到任何关于String中实际接受所述字符串值的方法的文档。我想的越多,我也不知道这样做的含义是什么(如果它甚至可能的话)。

我试过猴子修补String类

class String
  def initialize
    self = self.upcase
  end
end

或者

class String
  def new(str="")
    new_str = str.upcase
  end
end

但是我还没有找到关于如何实际初始化字符串的任何信息。

铊;博士

  1. 如何在所述字符串上将小写字符串转换为大写字母 初始化
  2. 如果有的话我是否应该注意     有可能吗?
  3. 感谢您的时间。

1 个答案:

答案 0 :(得分:1)

The solution here is not to boil the ocean and make every string in Ruby force everything to uppercase, but to uppercase the things that system needs if and when you provide it to that system.

Changing fundamental Ruby classes in this dramatic a way is bound to cause your entire code-base to implode. Many internals depend on being able to store arbitrary data in strings, and if those strings are arbitrarily uppercased you're in big trouble. It's like redefining what Integer#+ does. You can, but you really, really shouldn't. This would be akin to redefining the electrical charge of a proton. The universe would literally explode.

It's better to write some kind of adapter method that can operate on arbitrary strings or values and make sure they conform to whatever quirks or encoding your other system uses:

def to_arcahic(string)
  string.upcase
end

If, for example, they don't allow accented characters or emoji, you'll need to strip those out and/or convert them to something else. Maybe "é" becomes "E" or maybe you just delete it.