String Methods in ruby Code Example

Last Updated On Monday 12th Jul 2021

length – How long the string is

	print('Find String Length'.length) # 18
	

strip – Removes leading and trailing white space

	print('   I am the String with space   '.strip) # I am the String with space
	

to_i – Changes a string into a number

	print("123".to_i ) # 123
	

upcase, downcase – Changes the case of the string

	print('woohoo Ruby '.upcase ) # WOOHOO RUBY
print('WOOHOO RUBY '.downcase ) #  woohoo ruby
	

each_char – Loops through the string returning each character

	"ABC".each_char do |val|
 p val
end 
# "A"
# "B"
# "C"
	

include? – Returns true if a string is in another string

	print('Hello world'.include? 'World') # false
print('Im the New One'.downcase.include? 'one') # true
	

gsub – Substitutes a new string where a pattern is found

	print('Hello Washington, my name is Washington'.gsub 'Washington', 'Louisiana') # Hello Louisiana, my name is Louisiana