How To Deal with Strings in Ruby

How To Deal with Strings in Ruby

A string is a sequence of one or more characters that may consist of letters, numbers, or symbols.

Strings in Ruby are objects, and unlike other languages, strings are mutable, which means they can be changed in place instead of creating new strings.

You’ll use strings in almost every program you write. Strings let you display and communicate with your users using text. In fact, the page you’re reading right now is made up of strings displayed on your screen through your web browser. Strings are one of the most important fundamentals of programming.


What is a Ruby string?

Different languages have different ways of handling strings, so it's worth mentioning what strings mean in Ruby.

A string in Ruby is an object (like most things in Ruby).

You can create a string with either String::new or as literal (i.e. with the double quotes ""). But you can also create string with the special %() syntax With the percent sign syntax, the delimiters can be any special character.

Lets see a few examples.

"this is a string"
String.new("this is another string")
%(this is yet another string)
%/this is also a string/        

String methods

Strings are objects, and so you can call methods on the string object. And there are a ton of methods you can use.

1-How to convert a string to lower/upper case

"a string".upcase # => "A STRING"
"A STRING".downcase # => "a string"        

2-How to generate a random string

Let's say you need an eight character long random string. Here's one way to do it.

(0...8).map { (65 + rand(61)).chr }.join        

That line deserves some explanation.

First, we [create an array] with eight elements by using a range (i.e. (`0...8)`). Then, we change each one of those elements by mapping through the array. And as the value replacing the element, we generate a random character.

The character generation simply picks any number between 65 and 126 and calls `chr` on it to convert the int into its character representation.


3-How to check whether a string contains a substring

"a string".include?("str") # => true        

You could also use the element reference, which returns the string given as an argument if it matched.

"a string"["str"] # => "str"        

4-String concatenation

String concatenation is as simple as adding two strings together. And you would get a completely new string.

"abc" + "bcd" # => "abcbcd"        

You could also append one string to another.

"abc" << "bcd" # => "abcbcd"        

Note thought that this is not a new string. By appending a string, you are changing the initial string, you can verify this if you want.

my_string = "abc"
my_string + "bcd" # => "abcbcd"
my_string # => "abc"

my_string << "bcd"
my_string # => "abcbcd"        

5-Parsing a JSON string

JSON parsing is popular enough in the Ruby world so I thought it would be useful to include it here. Ruby provides a module out of the box for you to work with JSON.

require 'json'
string = %({"name": "John Doe"})
JSON.parse(string) # => {"name"=>"John Doe"}        

Note that you can't use single quotes for either the keys or the values. So this will not work.


6-How to read the contents of a file

Let's say you want to get the string representation of a file. Text or binary file, doesn't matter.

You can use the File module to read the contents into a string variable. Like so.

content = File.read("my_file.rb")        

7-How to remove substrings from strings

You would expect to find a delete method or remove to do that. I know I did.

But the fact is there's no such method. The method you would use for removing a substring from a string by using the `sub` method.

my_string = "this is my message"
my_string.sub(" message", "") # => "this is my"        

If you need to replace all the occurrences of the substring from the string, you can use `gsub` which stands for global.

my_string = "this is my message"
my_string.sub("i", "*") # => "th*s is my message"
my_string.gsub("i", "*") # => "th*s *s my message"        

You should not that those methods are non-destructive, meaning they return a new string. If you want to change the string in place, you would have to use the bang version (!).

my_string = "this is my message"
my_string.object_id # => 70144341686300
my_string.sub("i", "*").object_id # => 70144341783940
my_string.gsub("i", "*").object_id # => 70144341847500

my_string.sub!("i", "*").object_id # => 70144341686300
my_string.gsub!("i", "*").object_id # => 70144341686300        

8-How to split a delimited string and convert it to an array

If you have a string that uses some kind of separator, you can use it to create an array. Like so.

"a b c".split(" ") # => ["a", "b", "c"]        

Conclusion

In conclusion, mastering string manipulation in Ruby empowers developers to efficiently handle data. By familiarizing yourself with key methods like split and gsub, and experimenting with them in your projects, you'll enhance your coding skills. Keep exploring Ruby's vast library of string methods and practicing regularly to become more adept at working with strings. Happy coding!


Amazing work as expected from you 👏👏👏

İmpressive work bro 🔥❤️❤️

To view or add a comment, sign in

Others also viewed

Explore content categories