Checking character length in ruby

RubyString

Ruby Problem Overview


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 Solutions


Solution 1 - Ruby

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'

Solution 2 - Ruby

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

Solution 3 - Ruby

Instead of using a regular expression, just check if string.length > 25

Solution 4 - Ruby

Verification, do not forget the to_s

 def nottolonng?(value)
   if value.to_s.length <=8
     return true
   else
     return false
   end
  end

Solution 5 - Ruby

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

https://ruby-doc.org/core-2.4.0/String.html#method-i-size

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVijay SaliView Question on Stackoverflow
Solution 1 - RubyAndrew KirkView Answer on Stackoverflow
Solution 2 - RubyDanView Answer on Stackoverflow
Solution 3 - RubyelijahView Answer on Stackoverflow
Solution 4 - RubyKingsley MitchellView Answer on Stackoverflow
Solution 5 - RubyGinoView Answer on Stackoverflow