The substring is a part of string/variable. We can create substrings from a ruby string variable. We already dealt with substrings in Shell scripting in our early post. This substring can be one character length or multiple characters length. Below are some examples which we are going to have a look.
- Print first character of a string
- Print first n characters of a string
- Print nth character of a string
- Print from nth to mth character of a string
- Print last character of a string
- Print last n characters of a string.
Bit of background for Ruby string indexes
As Array’s have indexes to access elements of an array, Strings/Variables to have index values. The first character of a string index number is 0; the second one is 1 and so on. If you want to get last character index either you have to count some character in that string or use negative numbers. For example, if you want the last element of a string use -1, last but one use -2, etc.
We use Ruby IRB, which is an interactive Ruby Shell to show examples in this post. In this post, my string str1 is set to “The Linux Juggernaut.”
Print first character of Ruby variable
To print first character use index ‘0’ as shown below.
irb(main):001:0> str1 = 'The Linux Juggernaut' => "The Linux Juggernaut" irb(main):002:0> str1 => "T" irb(main):003:0>
Print first n characters of a Ruby string
Suppose if we want to write first two characters we use 0..1 as my index print.
irb(main):004:0> str1[0..1] => "Th"
How about first six characters of a string?
irb(main):005:0> str1[0..5] => "The Li"
Print nth character of a Ruby string
Suppose if I want to print the Nth character in a given variable, use that index number. In below example I want to write the 7th character of a string, I use str1 to get that value.
irb(main):006:0> str1 => "n"
Print from nth to mth character of a string
We can even slice strings by using start and end of index number. Suppose if we want to print between 7 to 9 characters use below example.
irb(main):007:0> str1[6..8] => "nux"
Print last character of a Ruby string
We can print the final character of a string by using its index value. As mention earlier we can access this in two ways. The first being no of position it is and other is -1.
irb(main):008:0> str1[-1] => "t"
irb(main):010:0> str1 => "t"
Print last n characters of a string.
We can print last N characters as well by giving a range as shown below.
irb(main):013:0> str1[5..-1] => "inux Juggernaut"
Print start to last but one character.
irb(main):014:0> str1[5..-2] => "inux Juggernau"