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.
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'
You could take any of the answers above that use the string.length method and replace it with string.size.
They both work the same way.
if string.size <= 25
puts "No problem here!"
else
puts "Sorry too long!"
end
Verification, do not forget the to_s
def nottolonng?(value)
if value.to_s.length <=8
return true
else
return false
end
end
Ruby provides a built-in function for checking the length of a string. Say it's called s
:
if s.length <= 25
# We're OK
else
# Too long
end
Instead of using a regular expression, just check if string.length > 25
Source: Stackoverflow.com