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.
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.
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.
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.
The size() is an inbuilt method in Ruby returns the size of the Set. It returns the number of elements in the set.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With