Basic Ruby – String

Tram Ho

String is probably the most important data type in any language. It is used in every kind of application we have ever written. It can also be called a Web raw material. Therefore, String is a great place to start learning about the Ruby programming language.

String basics

Strings are made up of strings of letters in a particular order. Let’s see what happens when we type a String (Do not use puts ) in Ruby.

Here we have entered a string called string and started with double quotes. And REPL (Read-Evaluate-Print Loop) will print the result of the line itself.
There is an important string – it is worth noting that it has no content, only consists of 2 double quotes. We call it an empty string .

Concatenation and interpolation

Two of the most important operations for strings are concatenation and interpolation . We will start with concatenation using the + operator.

Here, when connecting “foo” to “bar”, we get a new string called “foobar”.
Let’s look at concatenation strings in the context of using variables. That is, you should think that these are named boxes, and contain values ​​in them.

Variables and identifiers
If you have never been familiar with programming languages, you may be unfamiliar with the term variable. It is an essential idea in computer science. You can think of variables as a named box, which holds different content-values.
To make it easier to understand, you can see the image below. These are labeled box-boxes, which many schools provide to students to store clothes, books, backpacks … And we call the variable the location of the box, the label of the box is the name of the variable (or also called identifier), and what’s contained in the box is called the value of the variable.
In fact, these different definitions are often confused or confused. And variables are often used for any of the three concepts (location, label, or value).

Try making a specific example, we try to create 2 variables for first name and last name using the = sign as shown below:

Here, Link = has assigned the value “Michael” for first_name and “Hartl” for last_name.
And the first_name and last_name variables are being written according to the snake case rule (This is the most common convention for Ruby’s variable naming. In contrast, for Ruby’s Class, when naming will follow the CamelCase convention)

Once we have defined the variable names above, we can use them to match first and last names, while also inserting a space in between.

Another way to create a string is through interpolation using the # symbol and the curly braces # {…} .

Here, Ruby will automatically insert the value of the first_name variable into the string at the value we specified. Specifically, instead of using spaces, we can use interpolation as follows:

The above 2 expressions are equivalent, but I prefer the way of using interpolation, because we do not have to bother to insert spaces.

Single-quoted strings

In all the examples above, we’ve used double quotes, however Ruby also supports single quotes. For many different purposes, the two types are relatively similar.

The important difference here is, double quotes are known as raw strings . For example, Ruby will not be able to perform interpolation in strings using single quotes:

Observing the return value in double quotes, we see no requires a backslash to escape a combination of special characters such as # { .

Printing

Next we will learn how Ruby prints a string to the screen.
Use the puts function

This function acts as a side effect . It is more about fuction done than return value. puts "hello, world!" Will print the string on the screen and return nil. Nil is short for Latin nihil , meaning nothing .
Note that the spellings below are also perfectly valid in ruby. Puts can be called with parentheses.

A function similar to puts is print . It also prints the value to the screen as it is not automatically inserted into a newline character.

When using print, we can make a new line break by inserting the character n.

Attributes, booleans, and control flow

Everything in Ruby, including String, is an object. This means we can get a lot of useful information about strings along with the use of periods. to call utility attributes.
We will start by accessing the string attribute, which is a piece of data attached to the object. Specifically, in the console, we can use the length attribute to find the number of characters in a string.

Attribute length is especially useful when used for comparisons, such as checking the length of a string to compare with a specific value.

In the last line, we have used the == operator, in this case, Ruby is similar to other languages. (And note that, similar to Javascript, Ruby also supports the === operator)
The return values ​​in the above comparison always return true or false. It is called a boolean value.
Boolean values ​​are especially useful for control flow . It allows us to perform actions based on comparison results.

In the code above, we see behind the if statement is parentheses, and if statement ends with the end keyword. The back is required, but in Ruby those parentheses are optional, and we don’t usually write parentheses, as shown below:

The code above also follows the indentation rule. It is not related to Ruby’s required syntax but it is very important for reviewers or readers of code.

Code formatting
The sample code snippets in this article are written in a way that is easy to read and understand. Ruby doesn’t care about those formats, but it’s very important for developers or code readers.
Here are some general guidelines for writing good formatted code.

  • Indent to denote the structure of a block.
  • Use 2 spaces for indent. Many developers use 4 or 8 spaces, but I think 2 spaces is enough to denote a clear block, and also to save a narrow horizontal space.
  • Add a new line to indicate the logical structure. One thing I especially want to do is to add a new line after a sequence of value assignments, or variable initialization. This indicates that the initial setup has completed, and can start coding.
  • Limit the line to 80 characters. This is an old constraint, starting from the fact that the terminals were 80 characters wide. Many developers today violate this constraint, and consider it obsolete. However, in my experience, limited to 80 characters is a good rule, (for example, you have to use your code in documents with strict width requirements like in books. .) makes it easier for readers to read the code and understand it.

Next we will learn how to use the else function, which functions to perform the default if the first comparison is false.

In the first line, define the password by assigning it a new value, after reassigning the value, the password variable is 6, so password.length <6 will return false . As a result, the code inside the if function is not run, the program will run into the else branch, and print the result: "Password is long enough."
Ruby also has another keyword, elsif which means “else if” ,

Note that Ruby also allows us to put an if statement in the back, for cases where the code is only on one line.

And if statement is the negative of unless with the opposite comparison.

Basically we usually use if , however in some cases using unless may be better.

Combining and inverting booleans

Booleans can be combined or reversed using operators like & (“and”), || (“Or”), and ! (“Bang” or “not”).
Let’s start with && . When comparing booleans with && , both must be true for the result to be true . For example I say I want chips and baked potatoes. Then after combining it is true, if I answered correctly for both questions, “Do you want chips?” and “Do you want baked potatoes?”. If my answer is only one of two, then it will be false after the combination. The result of the combination is listed in the table below, which is called the truth table .

You can apply it to specific expressions as follows:

We see the result of y.length is 0, the result of x.length will be different from 0, when combined will return false so will jump to branch else to handle.
In contrast to the && operator, the || operator will return true if any value is true. Please refer to the table of values ​​below

Trying to apply the || operator, we get the following result:

In addition to && and ||, Ruby also supports negation through the “not” operator! (Pronunciation is “bang”). Its effect is reversing true to false, or false to true.

You can use as in the conditional sentence above, or use in combination with parentheses (, as shown below:

The above method is valid in Ruby, because it simply negates the statement x.length == 0 , and returns true .

However, in this case a more common way of writing, is to use the ! = (“Not equals”) operator.

Above, we no longer deny the whole expression so there is no need to use parentheses.

Bang bang

Not all booleans are a result of a comparison, in fact every Ruby object has a value of true or false in the boolean context. We can force Ruby to use boolean context by using operator !! (pronounced “bang bang”). Because! will convert true to false, and !! will bring them back to their original boolean state.

Using this trick, will allow us to see that a string like “foo” will return “true” in the boolean context.

And in fact, an empty string will also return true in the boolean context.

And, 0 is also true in Ruby.

In addition to false , there is also a Ruby object that returns false in the boolean context that is nil .

Methods

As mentioned above, Ruby’s object string has an attribute of length, but in reality Ruby does not have a basic distinction between attributes and methods , t can also think of it as messages to the object and Require the object to return a certain value.
In object-oriented programming languages, a string initialization will return specific methods. For example, the string will return the length method with the return of the length of the string.
There is an important class method that is a boolean method, which returns either true or false . Unlike other languages, Ruby allows punctuation in method names, and boolean methods in Ruby often end with question marks ? .

Here we see that the method is empty? will return true for empty string, and vice versa.
Can we use the empty method ? to rewrite the code above, so that they are more natural.

String also supports a lot of methods that help transform strings. For example, the string supports a downcase method that converts all characters to lowercase.

Note that the downcase method will return a new string without changing or changing the original string.

This method is quite useful in some situations, such as normalizing to lowercase letters in email addresses.

As you can probably guess, Ruby supports the opposite as well, which is upcase .

Also when looking at Ruby documents, there are many useful methods that support string handling. Try some of the methods below:

In the above list, we try to consider the following method:
include? other_str → true or false
This method takes other_str as an argument and will return true or false . Like the empty method ? , this method also ends with a question mark ? , indicating that this is also a boolean method. As we saw above, parentheses are optional (may or may not).

As seen above, the include method ? will return true , if it contains the specified string or characters.
In the third line above, did you find it confusing or difficult to understand the argument passed ? H ? Actually it was the previous syntax, and I checked with irb and found that ? H is the same as “h” .
Although, we can omit parentheses, but I prefer to use parentheses. Take a look at some of the extended examples below.

We see that String # include? (Writing to emphasize that include? Is an instance method of String ) can be called with diverse substring, it handles whitespace well, and case-sensitive case.

String iteration

Our final topic of String is iteration , we will practice iterating through each element of the object. Repetition is a basic topic in computer programming. We will learn later about how to restrict the use of iterations.
In the case of string, we will learn how to loop through each character. There are two main prerequisites for this problem. Firstly, we need to learn how to access a specific character in the string. The second is, we need to learn how to create a loop.
We can find a way to access a specific character by referencing the list method support for strings. Include the following:

Try looking at the following example, to see how it works:

From the example above, we see that Ruby supports square brackets to access elements and characters in the string, for example [0] will return the first character, [1] will return the second character. … (Each number such as 0,1,2 is called an index.)
Let’s look at the first example of the loop together, we will use the for loop to define an index of i value, and perform iterations through each value from 0 to 4. ( 0..4 )

This is a classic ruby ​​style loop, and is similar to other languages ​​like C and C ++ to JavaScript, Perl, or PHP. However, the difference is that, while other languages ​​have to use counting variables to increase each iteration, Ruby determines through special scope data types. So it will be more concise, compared to the iteration type of Javascript below:

When combined with the length method, we have an example of the for loop as follows.

There is a basic thing that, we should minimize the use of the for function, in the next article we will learn about the each function to see its advantages.

Over. We will explore other topics in Ruby together in the next article.
Source: Learn-enough

Share the news now

Source : Viblo