Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




RUBY - STRING


Say if you want to store your name or even a sentence in a variable. How would you do that?


The solution is the String datatype in Ruby.


There are two ways to declare a String :

  1. s = "Robert" or s = 'Robert'

  2. s = String.new("Robert");
    Note : String in a mutable class. i.e. Once the values are assigned to a String object,it can be modified or changed.

String Concatenation


Two or more Strings can be concatenated using the + operator or the << operator or the concat method.


If we have two Strings s1 and s2 :


s1 = "Suraj"

s2 = "Singh"
java_Collections


Three ways of concatenating Strings would be :

  1. "The name is " + s1 + s2

  2. "The name is " << s1 << s2

  3. "The name is ".concat(s1).concat(s2)

Example :



s1 = "Suraj"
s2 = "Singh"
puts "The name is " + s1 + s2


Output :



  The name is SurajSingh

In the above code we have created two Strings s1 and s2.


s1 = "Suraj"
s2 = "Singh"

And concatenated the String "The name is " with s1 and s2 using +.


puts "The name is " + s1 + s2

Concatenating a String and a Number


Now, let's say you are asked to print the String


Suraj Singh is 29 years old.

The Wrong way :


Let us solve it using the below way :


Example :



s1 = "Suraj"
s2 = "Singh"
age = 29;
puts s1 + " " + s2 + " is " + age +" years old."


Output :



+: no implicit conversion of Fixnum into String (TypeError)
  from add.rb:4:in <main>

But the above code will ended up with the above error.


Guess Why?


Let us look at the below line :


puts s1 + " " + s2 + " is " + age +" years old.";

The age variable is holding a number. And in Ruby you cannot concatenate a number and a String using the above code.


The Right way :


It can be corrected by two ways :


Using to_s


to_s is used to convert any other data type to a String. In this case we will be converting an integer to a String.


puts s1 + " " + s2 + " is "+age.to_s+" years old."

Example :



s1 = "Suraj"
s2 = "Singh"
age = 29
puts s1 + " " + s2 + " is "+age.to_s+" years old."



Output :



  Suraj Singh is 29 years old.

So, in the above code, we have corrected the problem,

"The 'age' variable is holding a number. And in Ruby you cannot concatenate a number and a String using the above code."

All we have done is, used to_s with age,


age.to_s

And now age is treated as a String.


And when we try concatenating age with the Strings s1 and s2,


puts s1 + " " + s2 + " is "+age.to_s+" years old."

It gives us the right output without any error.


Suraj Singh is 29 years old.

Let us look at the second way to solve the problem.


Using Interpolation - #{}


Interpolation, #{} is just like a placeholder, in which you can place any value irrespective of its data type.


puts "#{s1} #{s2} is #{age} years old."

Example :



s1 = "Suraj"
s2 = "Singh"
age = 29
puts "#{s1} #{s2} is #{age} years old."



Output :



  Suraj Singh is 29 years old.

So, in the above code, we have corrected the problem(Well! The second time),

"The 'age' variable is holding a number. And in Ruby you cannot concatenate a number and a String using the above code."

All we have done is, used Interpolation, #{} with the Integer, age and Strings s1 and s2,


"#{s1} #{s2} is #{age} years old."

#{age} is an expression which allows you to insert the number into a String.


#{s1} and #{s2} is just the same as above. i.e. It allows to enter the contents of a String variable within a String.


And when we try concatenating printing the output,


puts "#{s1} #{s2} is #{age} years old."

It gives us the right output without any error.


Suraj Singh is 29 years old.

Now, what if, you want a paragraph, separated by lines, to be assigned to a variable.


i.e. Let's say, you want to assign the below paragraph to a variable.

"We are putting newlines

after every text

and we get the same."

In such cases, you can use double quotes("") or %{}.


Declaring a multiline String with double quotes("") or %{}


Declaring a multiline String with double quotes("") :


Example :



x = "We are putting newlines
after every text 
and we get the same."


puts x


Output :



  We are putting newlines
  after every text
  and we get the same.

Declaring a multiline String with %{} :


Example :



x = %{We are putting newlines
after every text 
and we get the same.
}


puts x


Output :



  We are putting newlines
  after every text
  and we get the same.

Now, if you want to access a particular character of a String, how can you do that?


Say, you have a String "Hello". And you want the letter e to be assigned to a variable.


Let us see below.


Accessing the characters of a String


Example :



x = "Hello"
y = x[1]
puts y


Output :



  e

So, we have a string Hello,


x = "Hello"

And we have assigned Hello to a variable x.

java_Collections

Let us elaborate more, on how the String Hello is stored in the variable x.

java_Collections

So, just for the sake of understanding, you can assume the variable x is divided into 5 parts to store Hello.


Now, if you check from the front, the count starts from 0 and ends with 4.


Similarly, if you look from the reverse direction, the count starts from -1 and ends with -5.


So, if we look at the next line in the code,


y = x[1]

We are trying to access the 2nd location,

java_Collections

So, x[1] is referring to the 2nd location where e is stored.


y = x[1]

And we have assigned e to the variable y.

java_Collections

Note : The square brackets '[]' are used with the string type variable to get the variable at that position(i.e. x[1] refers to the 2nd location that contains 'e').

Now, if you look at the print statement,


puts y

The value of y is printed as output.

Output :



  e

Also, remember that x[1] and x[-4] is referring to the same location that has e. You can use the negative positions or positive. That is completely upto you.


Example :



x = "Hello"
y = x[-4]
puts y


Output :



  e

Next, let us see, how can we access a portion of a String. i.e. Say you want to take ell from the String Hello and store it in a different variable.


Accessing a chunk of letters/characters from a String


Example :



x = "Hello"
y = x[1,3]
puts y


Output :



  ell

So, we want to take the chunk of letters/characters from the String Hello and store it into the variable y.


And in the first line, we have stored Hello inside x.


x = "Hello"
java_Collections


Also, let us see the elaborated structure.

java_Collections

So, we want to take the chunk ell from Hello. And that happens in the next line.


y = x[1,3]

Just note, the position of e from ell is 1 and the position of the last l from ell is 3.


So, the statement x[1,3] simply refers, "Pick the chunk from index 1 to index 3".


And ell is assigned to the variable y.

java_Collections

And in the next line, we have the print statement,


puts y

That prints the chunk of letters ell.

Output :



  ell

String Replication


String Replication is a cool feature provided by Ruby. Say you want to print the name Robert 5 times.


The below code does it for you :


puts "Robert " * 5;

Output :



  Robert Robert Robert Robert Robert

Getting the length of a String


Example :



s = "Robert";
puts s.length;


Output :



  6

Getting a chunk of String


Say we want to get "ber" from the String "Robert".


Example :



s = "Robert";
puts s[2,3];


Output :



  ber

In s[2,3] the first number 2 is the index(index starts from 0), which is b. And the number 3 is the length of the String to be fetched.


So if you wanted to fetch bert. It would have been


puts s[2,4];

String Comparison

  1. The == operator



    Returns true if the condition matches else returns false.

    Example :



    s = "Robert"
    puts s == "Robert"
    


    Output :



      true

  2. The eql? Operator



    Returns true if the condition matches else returns false.

    Example :



    s = "Robert"
    puts s.eql?"Robert"
    


    Output :



      true

  3. The casecmp method



    Returns three values, -1, 0 and 1. If the condition matches, it returns 0. And returns 1 and -1 if the values don't match.

    Let us see them with the below example.

    Example :



    s = "Robert"
    puts s.casecmp "Robert"
    


    Output :



      0


    Now, since the condition matched, it returns 0.

    Let us see the next example.

    Example :



    s = "Robert"
    puts s.casecmp "Robera"
    


    Output :



      1


    Now, there is a mismatch, as we are trying to compare the String Robert

    s = "Robert"


    With Robera,

    puts s.casecmp "Robera"


    Now, since the values didn't match, it returned 1.

    But why not -1?

    Just note, there is just a mismatch of one letter i.e. The last letter of Robert is t and the last letter of Robera is a.

    Now, since a is less than t. It returns the value 1 in case of mismatch.

    Similarly, the below example also returns the value 1,

    Example :



    s = "Robert"
    puts s.casecmp "Rober"
    


    Output :



      1


    Because there are less letters in Rober.

    In the same way, the below example,

    Example :



    s = "Robert"
    puts s.casecmp "Roberz"
    


    Output :



      -1


    Now, there is a mismatch, as we are trying to compare the String Robert

    s = "Robert"


    With Roberz,

    puts s.casecmp "Robera"


    Now, since the values didn't match, it returned -1.

    But why not 1?

    Just note, there is just a mismatch of one letter i.e. The last letter of Robert is t and the last letter of Robera is z.

    Now, since z is greater than t. It returns the value -1 in case of mismatch.

    Similarly, the below example also returns the value -1,

    Example :



    s = "Robert"
    puts s.casecmp "Robertv"
    


    Output :



      -1


    Because there are more letters in Robertv.