Basic Ruby – Important objects in Ruby

Tram Ho

In the previous articles, we have learned about String and Array in Ruby. In this post, we’ll take a look at some of Ruby’s other important objects: math, dates, regular expressions, and hashes.

Math

Like most programming languages, Ruby supports a large number of math operations:

Pay great attention to division, as it is confusing:

Here, Ruby uses integer division. If you want to perform decimal division, add .0 to the numerator or denominator.

There are a lot of developers, including myself, who prefer to use irb as a simple calculator when computationally needed. The interface doesn’t seem very nice, but it’s pretty fast and powerful, with the ability to define variables.

More advanced operations

Ruby also supports a variety of advanced math operations through a module called Math , with useful functions such as constants, roots, and trigonometric functions.

The 2-dot symbol and uppercase letters ( Math :: PI ) above are characteristic of module constants . In addition, Ruby also supports a number of other trigonometric and power functions such as:

You can find out more details about the Math module here .

Math to string

In previous articles, we have learned how to convert strings to arrays (and vice versa) by using split and join . Similarly, Ruby also allows us to convert numbers and strings.
Probably the most common way to convert numbers to strings is by using the to_s (“to string”) method.

There are also other methods like to_i (“to integer”) and to_f (“to float”).

Time

Another frequently used object is Time (Technically it’s a class). Through Time learning, we get our first chance to learn about a new method, also known as a constructor function which is a basic Ruby way of creating new objects.
Until now, we used to use quotes or parentheses to directly initialize a new object, now we can use the new method to define a new object like a string or array …

and

Unlike strings or arrays, we cannot initialize Time with brackets or quotes, but we must use the new method.

When called without passing any arguments, Time.new will return the current time. In addition, we can also use Time.now to get the current time.

Similar to other Ruby objects, Time objects also support many different methods.

It is also possible to instantiate a Time object by passing specific date and time values.

By default, Time will use the local time zone, however it will cause difference between locations so we will use UTC time.

Finally, with Time, we can also perform math operations with them, such as addition, subtraction …

We can get the name of the current thing by creating an array containing the dates of the week. Then, use wday (weekday) as the array’s index.

Finally, we will update the hello app (using Sinatra) to display the date of the week.

Regular expressions

Ruby has full support for regular expressions , commonly referred to simply as regexes or regexps , which is a small and powerful language for matching patterns in text.
Mastering purely regular expressions is beyond the scope of this article, and probably very few master it. But the good news is, there’s a ton of regular expressions documented so we can dig into it.
It is important that you have a general idea of ​​regular expressions and be able to dig deeper when you need to use it.
Regexes has a reputation for being very brief and error prone, as famous programmer Jamie Zawinski said :

For some people, when they face a problem, they think “Ok, I’ll use regular expressions to solve it”. And so they run into 2 problems!

Fortunately, this situation has been greatly improved by useful web applications such as Rubular that allow us to visually construct regexes.

Rubular is a dedicated web regexes for Ruby. And let’s also learn some basic knowledge about regex in Ruby.
A regex is basically checking if a string matches a particular pattern. We can create a new regex using the new function. However, we often use the /…/ notation more often. The example below is a regex match with the US ZIP Code , consisting of 5 consecutive digits. zip_code = /d{5}/
If you use regular expressions you will remember the syntax, but you can also look up references like Rubular .
And now we will see how to know if a string matches the regex. And we will use the match method to test.

In practice, it’s more common to use it in a boolean context, like this:

Another common operation is the creation of an array of all matches. First we create a longer string and contain 2 zip codes.

To check if a string matches the regex, we use the String # scan method to find an array of matches.

We can also scan to find all words are capital letters.

Alternatively, you can refer to Rubular .

Splitting on regexes

In the previous section, we learned how to split a string based on space like this:

In this section, by manipulating the regex we can use a more powerful method. In regex a space is s and represents “one or more” as the plus sign + . And we get the following results:

This way we will get the same result for strings with lots of spaces, many tabs, or many newlines …

In addition, when calling the split function without parameters, Ruby automatically separates based on whitespace:

Hashes

The next data type we will find out is that hash , also known as associative array ( associative array ). You can think of a hash like an ordinary array, but it’s labeled for each value, not index. For example, instead of array [0] = 0 , the hash would be hash [“name”] = “Michael” . Therefore, each element in it is a value pair: including 1 label (key) and any value (valune). And we often call it key / value pairs.
And we usually set the value for label (key) to be of type string, for example we can create an object that stores the user’s first and last name as follows:

As you can see, we initialize an empty hash with {} braces. And assign the value to the element with square brackets [] (same as for array). And we can access the value of an element in the same way:

Note, in the last example above, the hash will return nil when the key doesn’t exist.
Instead of defining an element one by one for the hash using square brackets, we can use hashrocket => to define a series of elements.

Symbols

As we learned above, we used strings for hash keys, but now we use symbols more often. Symbols string looks similar, but it will come prefix a colon: and not be surrounded by quotes.

Symbols are a special Ruby data type, and are very rare in other languages. Therefore, they may seem a bit weird at first, but Ruby uses them a lot, so you will quickly get used to it.
Unlike string, not all characters are valid for symbols, however, if you enclose it in quotation marks as a type of string then it will run:

We can define a hash user using the following symbol:

The use of symbols for hashes is very common, so Ruby also supports hash initialization:

In the second syntax, we replaced the symbol / hashrocket symbol, with the name of the key and followed by a colon.

This writing style is similar to other languages ​​(such as Javascript), so this writing style is increasingly popular in the Ruby community. In short, the above two ways of writing are very popular, so we can write in any way.
However, you need to pay close attention to the different spelling between the two methods above to avoid confusion, that is: { :name => "Michael Hartl" } (with 2 dots before, and with hashrocket =>) and { name: "Michael Hartl" } (dot after)

Nested hashes

In fact, the hash may contain any value, even contain other hashes. And people call it nested hashes , it is frequently used in web development.

Hash iteration

Similar to arrays, hashes also support each method. For example, consider hash flash with the keys : success and : danger

Note that, while each in the array has only one variable in the code block, each in the hash will have two variables, key and value . Thus, for each loop, each method will iterate over a key-value pair.
Next, we’ll learn the inspect method, which returns a string with the wildcard it calls:

We have a short script for inspect which is:

Application: unique words

Now we will apply the knowledge of hashes above and give it a try. Our task is to extract words from a fairly long paragraph, and count the number of times that word appears.
Since our code looks long, we will create a Ruby file for easy manipulation. We can create the file by typing the following command:
$ touch count.rb
and initialize a variable containing string like so:

And the initialization of a hash is uniques containing unique words: uniques = {} .
Then define the words variable that contains one or more words, using regular expression: words = sonnet.scan(/w+/)
And use the scan method to return an array of string matches with the regex above.

Next, we’ll loop through the words array and do the following:

  • If the word already exists, add 1
  • If the word does not exist, the initialization is 1 Use operator + = to perform, as follows:

And finally the output: puts uniques
The full code will look like this:

Run the file count.rb , we get the following results:

 

Over. We will learn together about other topics in Ruby in the next posts.
Source: Learn-enough

Share the news now

Source : Viblo