Programming With Ruby Episode 6, Strings

Covered in this episode:

  • String Literals
  • String Expressions
  • String Methods
  • Regular Expressions
  • Getting User Input (gets)

Transcript:

Hello Everyone and Welcome to Programming With Ruby Episode 6,
Strings. I’m Tyler, your presenter. This is brought to you by
manwithcode.com

In this episode I will be telling you what string literals are. I will
show you expressions you can use with strings, which are similar but
still different than expressions with numbers. I will show you useful
methods strings have. I will show you how to use regular
expressions. Finally I will teach you how to get input from the
user.

On to the Code!

String Literals

According to wikipedia, string literals are the representation of a
string value within the source code of a computer program. For
example:

puts "Hello World" # Hello World is the string literal

String Expressons

The only string expressions are the plus and multiplication sign. The
plus sign connects strings together, the multiplication sign repeats a
string a certain number of times.
Let me show you how it works:

"Hello " + "World!" #=> "Hello World!"
"Hello " * 3 #=> "Hello Hello Hello"

String Methods

Here are some useful String methods:
empty? tells you if you are dealing with an empty string
length tells you how long a string is
each_char lets you iterate over each character
capitalize capitalizes the first character
upcase makes all characters upper case
downcase makes all characters lower case

Regular Expressions

Regular expressions are a way to match elements in other strings. It
is easier to show you than to describe to you, so here we go!

The simplest is substitution:

"Hello World".sub("Hello", "Goodbye")
#=> "Goodbye World"

But if you have more than one hello:

"Hello Hello Hello".sub("Hello", "Goodbye")
#=> "Goodbye Hello Hello"

This happens because the sub method only replaces the first occurrence
of “Hello”. The gsub method fixes this:

"Hello Hello Hello".gsub("Hello", "Goodbye")
#=> "Goodbye Goodbye Goodbye"

What if you want to manipulate parts of a string using regular
expressions. The scan method is what you want!

# /n means new line
"Who are you".scan(/../) { |x| puts x }
#=> Wh\no \nar\ne \nyo
# With no whitespace:
"Who are you".scan(/\w\w/) { |x| puts x }
#=> Wh/nar/nyo

Regular Expressions are a vast topic that I can’t completely cover
here, so do a Google search to find out more.

Getting User Input

You can get user input with the “gets” method:

a = gets
# The user inputs: I like pie
puts a #=> "I like pie"

That wraps it up for todays episode.

Don’t forget to donate, the link is to the right of this video

If you have any questions or comments, leave a comment on this page or
email me at tyler@manwithcode.com

Bye!