find the length of a string in ruby

To find the length of a string in Ruby, you can use any of the following three methods:

  1. length: This method returns the length of the string.
main.rb
str = "hello world"
puts str.length #=> 11
43 chars
3 lines
  1. size: This method is an alias of length method. It also returns the length of the string.
main.rb
str = "hello world"
puts str.size #=> 11
41 chars
3 lines
  1. count: This method can also be used to find the length of the string by passing '' as an argument.
main.rb
str = "hello world"
puts str.count('') - 1 #=> 11
50 chars
3 lines

All three methods achieve the same result, so use the one that you find most readable and convenient.

related categories

gistlibby LogSnag