Sie sind auf Seite 1von 23

2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

BECOME A BETTER DEVELOPER RUBY DEEP DIV

Ruby String Methods (Ultim


/ By Jesus Castello / 17 COMMENTS

A string is a sequence of characters.

Strings are objects so they have a lot of methods you can use to d

In this article you’ll discover the most useful Ruby string methods

Share this post! = Share q Tweet - Share


Contents [hide]

1 How to Get The String Length


2 What is String Interpolation?
3 How to Extract a Substring
4 How to Find Out If a String Contains Another String
5 How to Pad a Ruby String
6 Compare Strings Ignoring Case
7 How to Trim a String & Remove White Space
8 String Prefix & Suffix
9 Convert a String to An Array of Characters
10 Convert an Array to a String
11 Convert a String Into An Integer
12 Check If A String Is A Number

https://www.rubyguides.com/2018/01/ruby-string-methods/ 1/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

13 How to Append Characters


14 Iterate Over Characters Of a String in Ruby
15 How to Convert a String to Upper or Lowercase in Ruby
16 How to Create Multiline Strings
17 How to Replace Text Inside a String Using The Gsub Method
18 How to Remove the Last Character From a String
19 How to Change String Encodings
20 Counting Characters
21 Summary
21.1 Related

How to Get The String Leng


Easy:

"ruby".size
# 4

Share this post! = Share q Tweet - Share


You can also use length , instead of size , they do the same thi

What is String Interpolation


String interpolation allows you to combine strings together:

name = "Jesus"

puts "Hello #{name}"

What some people don’t know is that you can have actual code ins

https://www.rubyguides.com/2018/01/ruby-string-methods/ 2/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Here’s an example:

puts "The total is #{1+1}"

# "the total is 2"

Ruby calls the to_s method on the string interpolation block, this
string.

How to Extract a Substring


If you only want part of a string, instead of the whole string, then y
substring.

Like this:

string Share this post!


= "abc123" = Share q Tweet - Share

string[0,3]
# abc

string[3,3]
# 123

The first number is the starting index & the second number is how

You can also use a range if you want to do something like “get all t

Example:

string = "abc123"

https://www.rubyguides.com/2018/01/ruby-string-methods/ 3/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

string[0..-2]
# "abc12"

The first index is the starting index & the second index is the endin
second to last character, and -1 is the end of the string.

If you want to remove or replace the substring.

You can do this:

string[0..2] = ""

p string
# "123"

How to Find Out If a String C


Share this post! = Share q Tweet - Share

Another String
What’s the easiest way to find if a string is included in another strin

The include? method:

string = "Today is Saturday"

string.include?("Saturday")
# true

You can also use the index method:

https://www.rubyguides.com/2018/01/ruby-string-methods/ 4/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

string = "Today is Sunday"

string.index("day")
# 2

This method looks for partial words & instead of returning true or
the start of this string is found.

In this example index is finding the “day” in “Today”.

If you want to find patterns (like all the words containing the word
expressions.

How to Pad a Ruby String


One way to pad a string is to use the rjust method with two arg

Share this post! = Share q Tweet - Share


binary_string = "1101"
binary_string.rjust(8, "0")

# "00001101"

If you want to pad to the right you can use ljust :

binary_string = "1111"
binary_string.ljust(8, "0")

# "11110000"

Compare Strings Ignoring C


https://www.rubyguides.com/2018/01/ruby-string-methods/ 5/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Because string comparison is case-sensitive you want to make su


are in the same case.

The common way to do that is to make both sides of the equation

Example:

lang1 = "ruby"
lang2 = "Ruby"

lang1.upcase == lang2.upcase

There is also a casecmp? method that does a case-insensitive co

Stick with the example above.

How to Trim a String & Rem


Share this post! = Share q Tweet - Share

Space
When reading data from a file or a website you may find yourself w

You can remove that extra space with the strip method:

extra_space = " test "


extra_space.strip

# "test"

If you only want to remove the white space from one of the sides (
rstrip methods instead.

https://www.rubyguides.com/2018/01/ruby-string-methods/ 6/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

String Pre x & Su x


You can use the start_with? method to check if a string starts

Here’s an example:

string = "ruby programming"

string.start_with? "ruby"
# true

There’s also an end_with? method:

string = "ruby programming"

string.end_with? "programming"
# true

Share this post! = Share q Tweet - Share


In addition, Ruby 2.5 introduced the delete_prefix & delete
useful to you.

Here’s an example:

string = "bacon is expensive"

string.delete_suffix(" is expensive")

# "bacon"

Convert a String to An Array


https://www.rubyguides.com/2018/01/ruby-string-methods/ 7/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Taking a string & breaking it down into an array of characters is ea

Example:

string = "a b c d"

string.split
# ["a", "b", "c", "d"]

By default split will use a space as the separator character, but


method to specify a different separator.

Here’s how you can split a list of comma-separated values (CSV):

csv = "a,b,c,d"

string.split(",")
# ["a", "b", "c", "d"]
Share this post! = Share q Tweet - Share

But if you are working with CSV data specifically you may want to c
standard library. This class can do things like reading column head

Convert an Array to a String


If you would like to take an array of strings & join these strings into
method.

Example:

arr = ['a', 'b', 'c']

https://www.rubyguides.com/2018/01/ruby-string-methods/ 8/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

arr.join
# "abc"

It’s also possible to pass an argument to join , this argument is t

Example:

arr = ['a', 'b', 'c']

arr.join("-")
# "a-b-c"

Convert a String Into An Int


If you want to convert a string like "49" into the Integer 49 you c

Example:
Share this post! = Share q Tweet - Share

"49".to_i

Notice that if you try this with a string that contains no numbers th

Example:

"a".to_i
# 0

Check If A String Is A Numb


https://www.rubyguides.com/2018/01/ruby-string-methods/ 9/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Would you like to know if a string is made of only whole numbers?

You can do this:

"123".match?(/\A-?\d+\Z/)
# true

"123bb".match?(/\A-?\d+\Z/)
# false

“ Note: The match? method was introduced in Ruby 2.4, you c


mark) on older versions.

This code uses a regular expression, let me translate it for you:

“From the start of the string ( \A ) check if there is an optional das


Share this post! = Share q Tweet - Share
make sure there are some numbers in there ( \d+ ) & nothing else

How to Append Characters


You can build up a big string from smaller strings by appending ch
call this string concatenation.

Here’s how to do that using the << method:

string = ""

string << "hello"


string << " "
string << "there"

https://www.rubyguides.com/2018/01/ruby-string-methods/ 10/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

# "hello there"

Don't use += for string concatenation because that will create a n


for performance!

Iterate Over Characters Of a


Sometimes it's useful to work with the individual characters of a st

One way to do that is to use the each_char method:

"rubyguides".each_char { |ch| puts ch }

You can also use the chars method to convert the string into an
each on this array to iterate.
Share this post! = Share q Tweet - Share

Example:

array_of_characters = "rubyguides".chars
# ["r", "u", "b", "y", "g", "u", "i", "d", "e", "s"]

How to Convert a String to U


Lowercase in Ruby
If you would like to convert a string to all upper case you can use t

Example:
https://www.rubyguides.com/2018/01/ruby-string-methods/ 11/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

"abcd".upcase
# "ABCD"

And if you want to convert to lower case you can use the downca

Example:

"ABCD".downcase
# "abcd"

How to Create Multiline Str


You can create multi-line strings in two different ways.

One is by using heredocs:


Share this post! = Share q Tweet - Share

b = <<-STRING
aaa
bbb
ccc
STRING

And another is by using %Q :

a = %Q(aaa
bbb
ccc
)

https://www.rubyguides.com/2018/01/ruby-string-methods/ 12/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

How to Replace Text Inside


The Gsub Method
If you want to replace text inside a string use the gsub method.

Let's replace the word "dogs" with "cats":

string = "We have many dogs"

string.gsub("dogs", "cats")

# "We have many cats"

If you want to remove the string use an empty string as the 2nd ar

Example:

Share this post! = Share q Tweet - Share


string = "abccc"

string.gsub("c", "")

# "ab"

Now:

The gsub method returns a new string.

If you want to apply the changes to the original string you can use

The gsub method also takes regular expressions as an argument s


exact words.
https://www.rubyguides.com/2018/01/ruby-string-methods/ 13/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Here's an example:

string = "We have 3 cats"

string.gsub(/\d+/, "5")

# "We have 5 cats"

This replaces all the numbers ( \d+ ) in the string with the number

Replace Text in Ruby

Share this post! = Share q Tweet - Share

One more way to use this method, with a block:

title = "the lord of the rings"

title.gsub(/\w+/) { |word| word.capitalize }

https://www.rubyguides.com/2018/01/ruby-string-methods/ 14/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

# "The Lord Of The Rings"

What about gsub vs sub ?

Well, sub is the same as gsub , but it will only replace the first ma

Gsub replaces ALL matches.

How to Remove the Last Ch


String
If you are asking the user for some input (using the Kernel#gets m
character ( \n ) at the end of your string, this prevents you from co

Example:

Share this post! = Share q Tweet - Share


puts "What's your name?"
name = gets

# type something...

The best way to remove that extra newline character ( \n ) is to us

Example:

name = gets.chomp

Since Ruby 2.3 the chomp method takes an optional argument tha
you want to remove.
https://www.rubyguides.com/2018/01/ruby-string-methods/ 15/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Example:

"abcd?".chomp("?")
# "abcd"

And if the character is not there it will return the original string.

How to Change String Enco


Strings are stored as a sequence of bytes, they are turned into the
their encoding.

For example, the number 65 in the ASCII encoding represents the

But there are also more complex encodings, like UTF-8, which allo
different languages (Chinese, etc.) & even emojis.
Share this post! = Share q Tweet - Share
To find out the current encoding for a string you can use the enco

"abc".encoding

# Encoding:UTF-8

When reading a file from disk or downloading some data from a w


problems.

You can often fix that problem by enforcing the encoding .

Like this:

https://www.rubyguides.com/2018/01/ruby-string-methods/ 16/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

"abc".force_encoding("UTF-8")

Counting Characters
You can count how many times a characters appears in a string by

Example:

str = "aaab"

str.count("a")
# 3

str.count("b")
# 1

Summary Share this post! = Share q Tweet - Share

You learned about many string methods, like join & split to break d
replace text inside strings & strip to trim out extra white space.

Since you may want to reference this page later make sure to book
friends

Thanks for reading!

https://www.rubyguides.com/2018/01/ruby-string-methods/ 17/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Related

How to Use Ruby Conversion Methods Why Do We Use Nil?


September 18, 2018 May 30, 2018
In "Programming" In "Programming"

Share this post!

 Tweet  Share

17 comments

Maddox says
last year

Nice post. Very helpful roundup and explanation of st


Share this post! = Share q Tweet - Share

Jesus Castello says


last year

Thanks for reading!

Tom Connolly says


last year

https://www.rubyguides.com/2018/01/ruby-string-methods/ 18/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Thanks for your informative posts. Just the right size

Jesus Castello says


last year

Thanks for reading Tom! Let me know if there is a


to cover

David C says
last year

Really love your guides, simple, effective to the point.


Share this post! = Share q Tweet - Share

Jesus Castello says


last year

Thanks David! I’m glad you find them useful

Abdullah H says
last year

https://www.rubyguides.com/2018/01/ruby-string-methods/ 19/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

In your post, you mentioned the method ‘casecmp?’


string comparisons. However, you also recommende
comparing up/downcased strings.

What is the downside to using ‘casecmp?’?

Jesus Castello says


last year

Abdullah, I don’t think there is any real downside,


would use in Ruby.

Share this post! = Share Tweet - Share


Tara saysq
last year

I found your page because I was trying to fi


downcase with the spaceship operator to
up demanding casecmp, and we use rubo
faster when benchmarking, which is why I
us that way. Meanwhile, I’m still not gettin
need to disable rubocop there, but that’s n

Jesus Castello says


https://www.rubyguides.com/2018/01/ruby-string-methods/ 20/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

last year

Taking a look at the source code of


performance rule.

The example given is this:

str.casecmp('ABC').zero?

I don’t like this at all, so I would avo


performance boost.

Tara says
last year

Share this post! = Share q Tweet


- Share
I ended up getting it to work just fin
process our pull requests, as did th
start seeing more of it. In any case,
piece of info helps out here!

Simon says
last year

Hi there! Great article, I am missing “<<~ curly doc”, m

Keep up the good work and thank you so much for th

https://www.rubyguides.com/2018/01/ruby-string-methods/ 21/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

Jesus Castello says


last year

Hi Simon! Thanks for reading

Matthew Bell says


last year

In your “How to Remove the Last Character From a S


says “And if the character is not there it will return the
string not array. Love the article though it didn’t occu
string object every time and String#<< does proper st
Share this post! = Share q Tweet - Share
string! Cheers.

Jesus Castello says


last year

Good catch! It’s fixed now, thank you.

Tushar Kulkarni says


https://www.rubyguides.com/2018/01/ruby-string-methods/ 22/23
2/6/2019 Ruby String Methods (Ultimate Guide) - RubyGuides

last year

Thanks. This was very informative and helpful.

Jesus Castello says


last year

Thanks for reading

Comments are closed

Sign up to my newsletter & grab your FREE guide!

https://www.rubyguides.com/2018/01/ruby-string-methods/ 23/23

Das könnte Ihnen auch gefallen