I'd use something like:
def validate_usr(username)
!!username[/\A\w{4,16}\z/]
end
validate_usr('foo') # => false
validate_usr('foobar') # => true
validate_usr('FooBar') # => true
validate_usr('Foo Bar') # => false
validate_usr('12345678901234567') # => false
\w
is the set [a-zA-Z0-9_]
, which includes uppercase too. If you don't want upper-case then use [a-z0-9_]
for the set.
[/\A\w{4,16}\z/]
is a String shortcut for applying a pattern to the string and returning the match. As the tests ran username[/\A\w{4,16}\z/]
returned:
username[/\A\w{4,16}\z/] # => nil, "foobar", "FooBar", nil, nil
!!
converts "truthy"/"falsey" to true
/false
, so here are the actual results:
!!username[/\A\w{4,16}\z/] # => false, true, true, false, false
The end result is the method returns the desired true/false results only with less code.
I used \z
rather than \Z
because you're testing usernames, presumably for correctness prior to creating an account. \z
applies the test to the entire string, whereas \Z
will ignore a trailing line-end. If your code were to somehow allow a user to create a name with a trailing line-end \Z
would not give you an accurate validation result:
"foobar\n"[/\A\w{4,16}\Z/] # => "foobar"
"foobar\n"[/\A\w{4,16}\z/] # => nil