๐ŸŽ“ A1Learner
๐Ÿ”

Ruby String Methods

A string method is a built-in tool that works on a string. Most string methods make a new string and leave the first string as it was.

Counting characters

length counts the characters in a string. The count prints as a number.

word = "Ruby"
puts word.length

upcase makes a new string

upcase makes a new string in capital letters. The next print shows the first string still in small letters.

word = "ruby"
puts word.upcase
puts word

Small letters and a flip

downcase makes every letter small. reverse flips the string so it reads back to front.

puts "RUBY".downcase
puts "ruby".reverse

Asking with include?

include? asks whether a string holds a piece of text. The answer prints as true or false.

puts "ruby".include?("ub")
puts "ruby".include?("zz")

Cutting a string into parts

split cuts a string at each comma. p prints the parts together as one array value.

p "red,green,blue".split(",")

Example

word = "hello"
puts word.length
puts word.upcase
puts word.reverse
puts word.include?("ell")
puts word

Key points

  • length counts the characters in a string.
  • upcase makes a string with every letter capital.
  • downcase makes a string with every letter small.
  • reverse makes a string that reads back to front.
  • include? checks whether a string holds a smaller piece of text.
  • split cuts a string into parts at a chosen mark.

In this example, word holds the string hello. length counts five characters and prints 5. upcase prints HELLO as a new string. reverse prints olleh. include? prints true because hello holds ell. The last print shows word still as hello.

Note

A method name that ends with ? gives true or false as its answer.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

A program sets word to "ruby" and prints word.upcase. What does a later print of word show?