Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 海关。你是海关吗?红宝石色_Ruby - Fatal编程技术网

Ruby 海关。你是海关吗?红宝石色

Ruby 海关。你是海关吗?红宝石色,ruby,Ruby,是否可以在Ruby中创建自定义的Is\u? 我有一个字符串,可以是UID,也可以是昵称,我需要检查并确定 UID:001ABC123(以3个数字字符开头,以6个字母数字字符结尾) 昵称:john(可以是任何东西,但不能以数字开头) 我希望能够做到: t = '001ABC123' if t.is_a? UID ... end 有可能吗?ruby的一大优点是可以重新打开任何类。因此,这一实现可能如下所示: class String def is_a?(type) r

是否可以在Ruby中创建自定义的
Is\u?

我有一个字符串,可以是UID,也可以是昵称,我需要检查并确定

UID:
001ABC123
(以3个数字字符开头,以6个字母数字字符结尾)

昵称:
john
(可以是任何东西,但不能以数字开头)

我希望能够做到:

t = '001ABC123'

if t.is_a? UID
  ...
end

有可能吗?

ruby的一大优点是可以重新打开任何类。因此,这一实现可能如下所示:

class String
    def is_a?(type)
        return true if type == UID
    end
end
class UID < String
  def self.=== str
    str === '123'
  end
end

class UID2 < String
  def self.=== str
    str === '456'
  end
end

case '456'
when UID
  puts 'uid'
when UID2
  puts 'uid2'
else
  puts 'else'
end

ruby的一个优点是可以重新打开任何类。因此,这一实现可能如下所示:

class String
    def is_a?(type)
        return true if type == UID
    end
end
class UID < String
  def self.=== str
    str === '123'
  end
end

class UID2 < String
  def self.=== str
    str === '456'
  end
end

case '456'
when UID
  puts 'uid'
when UID2
  puts 'uid2'
else
  puts 'else'
end

不要污染全球
字符串
-使用改进:

class UID < String
end

module CustomStringIsA
  refine String do
    def is_a? what
      if what == UID
        self == '123'
      else
        super
      end
    end
  end
end

puts '123'.is_a?(UID) # false

using CustomStringIsA
puts '123'.is_a?(Fixnum) # false
puts '123'.is_a?(UID) # true

不要污染全球
字符串
-使用改进:

class UID < String
end

module CustomStringIsA
  refine String do
    def is_a? what
      if what == UID
        self == '123'
      else
        super
      end
    end
  end
end

puts '123'.is_a?(UID) # false

using CustomStringIsA
puts '123'.is_a?(Fixnum) # false
puts '123'.is_a?(UID) # true

如果您正在寻找执行检查的简洁方法,为什么不使用正则表达式并使用
=~
运算符进行匹配呢

这就像使用自定义
是一个?
一样简洁,并且不需要弄乱
字符串

例如:

UID = /^[[:digit:]]{3}[[:alnum:]]{6}$/

t = '001ABC123'

if t =~ UID
   #...
end

如果您正在寻找执行检查的简洁方法,为什么不使用正则表达式并使用
=~
运算符进行匹配呢

这就像使用自定义
是一个?
一样简洁,并且不需要弄乱
字符串

例如:

UID = /^[[:digit:]]{3}[[:alnum:]]{6}$/

t = '001ABC123'

if t =~ UID
   #...
end

此解决方案为
'string'返回
nil
。它是一个?(string)
,应该是
true
,很可能会破坏第三方库中的某些内容。此解决方案为
'string'返回
nil
。它是一个?(string)
,这应该是
正确的
,并且很可能会破坏第三方库中的某些东西。将
全局设置为字符串是一个非常糟糕的主意。如果项目中的其他任何地方有人决定也将
is_a
方法添加到字符串中,您将得到一些有趣的bug。将
is_a
全局添加到字符串中是一个非常糟糕的主意。如果项目中的其他任何地方有人决定也在字符串中添加
is\u一个
方法-您将得到一些有趣的bug。