Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking character length in ruby

Tags:

string

ruby

I got stuck in another situation: our users enter a text to be stored in a variable. The condition for that text is it can be allowed to enter only 25 characters, Now I have to write a regular expression which will check the condition, kindly help me out in this.

like image 696
Vijay Sali Avatar asked Jan 06 '12 05:01

Vijay Sali


People also ask

How do you count characters in Ruby?

Ruby | String count() Method count is a String class method in Ruby. In this method each parameter defines a set of characters to which is to be counted. The intersection of these sets defines the characters to count in the given string. Any other string which starts with a caret ^ is negated.

How do I print the length of a string in Ruby?

The simplest way to get the length of a string is to use Ruby's built-in length method. It returns the length of the characters in the specified string. The method will return the characters in the string, including whitespace characters.

How do I use GSUB in Ruby?

gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.

What does .size do in Ruby?

The size() is an inbuilt method in Ruby returns the size of the Set. It returns the number of elements in the set.


1 Answers

I think you could just use the String#length method...

http://ruby-doc.org/core-1.9.3/String.html#method-i-length

Example:

text = 'The quick brown fox jumps over the lazy dog.' puts text.length > 25 ? 'Too many characters' : 'Accepted' 
like image 135
Andrew Kirk Avatar answered Sep 24 '22 10:09

Andrew Kirk