Reputation: 389
Is it possible to create a custom is_a?
in Ruby?
I have a string that can be either a UID or a nickname that I need to check and decide.
UID: 001ABC123
(starts with 3 numeric and ends in 6 alphanumeric characters)
Nickname: john
(can be anything but never starts with a number)
I want to be able to do:
t = '001ABC123'
if t.is_a? UID
...
end
Is it possible?
Upvotes: 0
Views: 275
Reputation: 18762
If you are looking for succinct way of doing the check, why not use regular expression and match using =~
operator.
This is as neat as using custom is_a?
and does not require messing up with String
class.
For example:
UID = /^[[:digit:]]{3}[[:alnum:]]{6}$/
t = '001ABC123'
if t =~ UID
#...
end
Upvotes: 7
Reputation: 18474
Not to pollute global String
- use refinements:
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
But better use ===
, so you can then use case
like this:
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
Upvotes: 0
Reputation: 11921
One of the great things about ruby is that you may reopen any class. So an implementation of this may look like this:
class String
def is_a?(type)
return true if type == UID
end
end
Upvotes: -2