Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating and Printing Strings
3.
Accessing Characters and Substrings in ruby
4.
Substrings
5.
Frequently Asked Questions
5.1.
How do you access the characters in a string in Ruby?
5.2.
How do you get substrings in Ruby?
5.3.
How do you get the first 3 characters of a string in Ruby?
5.4.
How do you declare a string in Ruby?
5.5.
How do you get the first character of a string in Ruby?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Accessing Characters and Substrings in ruby

Author Alok Pandey
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Strings will appear in practically every program you build. Strings allow you to use text to display information and communicate with your users. The website you're reading right now is made up of strings that your web browser shows on your screen. Strings are one of the most crucial programming concepts.

A sequence of characters is referred to as a string. It could be made up of letters, numbers, or symbols. Because strings are objects, you can use various methods to manipulate them. String's object holds and controls an arbitrary sequence of the bytes that commonly represents a sequence of characters.

Creating and Printing Strings

Before accessing Characters and substrings in ruby let's try to understand how to create the string. For creating the string, one can just put the sequence of characters either in single quotes or double quotes. Also, the user can store the string in any variable. In Ruby, we don't need to specify the variable's data type.

Code

my_name = "Coding Ninjas"
my_tagline = ‘Skill for Life’
puts my_name
puts my_age

 

Output

Coding Ninjas
Skill for Life

 

The puts method prints the entire string you specify but also adds a newline character to the end of the string for you.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Accessing Characters and Substrings in ruby

A string in Ruby 1.8 is equivalent to an array of bytes or 8-bit character codes. The length or size method determines the array's length. One can get or set elements of the array simply by specifying the character number(index) within square brackets:

s = 'hello'; 

print s[0]
print s[s.length-1]
print s[-1] 
print s[-2] 
print s[-s.length]
print s[s.length]   

 

Output

h
o
o    # Another way of accessing the last character
l     # The second-to-last character
h     # Another way of accessing the first character
nil   # There is no character at that index

 

Negative array indexes specify a 1-based position from the string's end. Also, if you try to access a character beyond the end of the string, Ruby does not throw an exception; instead, it returns nil.

When you index a single character in Ruby 1.9, you get single-character strings instead of character codes. Keep in mind that random access to characters is less efficient than access to the underlying bytes when working with multibyte strings with characters encoded using variable numbers of bytes:

s = 'hello'; # Ruby 1.9
print s[0]  
print s[s.length-1]    
print s[-1] 
print s[-2] 

 

Output

h  # The first character of the string, as a string
o  #  The last character 'o'
o  # Another way of accessing the last character
l   # The second-to-last character

Also check out - Substr C++

Substrings

A substring is a group of characters contained within a larger string. Ruby does not have a substring method. We rely on ranges and expressions instead. We use two comma-separated operands for accessing the substring in ruby between the square brackets. The first operand specifies an index (which may be negative), and the second specifies a length (which must be non-negative). The result is the substring that begins at the specified index and continues for the specified number of characters:

s = "HELLO"
print s[0,2]  # "HE"
print s[-1,1]  
print s[0,0]  
print s[0,10]  
print s[s.length,1]  
print s[s.length+1,1]  
print s[0,-1]  

 

Output

O  # Returns a string, not the character code
“” # A zero-length substring is always empty
HELLO # Returns all the characters that are available
“”   # There is an empty string immediately beyond the end
nil  #It is an error to read past that
nil  #Negative lengths don't make any sense

When you assign a string to a string indexed like this, the new string replaces the given substring. This is a deletion if the righthand side is an empty string, and an insertion if the lefthand side is zero-length.

s = "hello"
s[0,1] = "H" # Replace first letter with a capital letter
s[s.length,0] = " world" # Append by assigning beyond the end of the string
s[5,0] = "," # Insert a comma, without deleting anything
s[5,6] = "" # Delete with no insertion; s == "Hellod"


Check out this problem - Longest String Chain

Frequently Asked Questions

How do you access the characters in a string in Ruby?

One can access the characters in a string in Ruby simply by specifying the character number(index) within square brackets.

How do you get substrings in Ruby?

Ruby does not have a substring method. We use two comma-separated operands for accessing the substring in ruby between the square brackets. The first operand specifies an index (which may be negative), and the second specifies a length (which must be nonnegative).

How do you get the first 3 characters of a string in Ruby?

In Ruby, we use the square brackets syntax [] to access the characters of a string by passing the start index and length. To access the first 3 characters we will use the syntax[0,3]

How do you declare a string in Ruby?

one can just put the sequence of characters either in single quotes or double-quotes. Also, the user can store the string in any variable. In Ruby, we don't need to specify the variable's data type.

How do you get the first character of a string in Ruby?

To get the first character of a string, we can utilise the built-in chr method. Similarly, we can get the first character of a string using the subscript syntax [0].

Conclusion

In this article, we have extensively discussed the methods of accessing Characters and substrings in ruby programming.

We hope that this blog has helped you enhance your knowledge regarding accessing Characters and substrings in ruby programming and if you would like to learn more, check out Official Documentation and  the following articles on  


Recommended problems -

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. 

Enroll in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Previous article
String Operators in Ruby
Next article
Iterating Strings in Ruby
Live masterclass