Ruby's basic data type (iii)

Source: Internet
Author: User
Tags ruby on rails
Foreword
In the previous section we introduced the use of constants and variables. In this section we start to introduce some basic types in Ruby.

Numeric type (Fixnum, Bignum, Float)
Ruby's numeric types include integers and floating-point numbers. Integers include Fixnum and Bignum. Fixnum can hold integers that are one bit shorter than a physical word. When an integer exceeds the Fixnum range, it will be automatically converted to Bignum type, and the Bignum type range can only be limited by physical memory.

If an arithmetic operation is performed on a Bignum integer, the final result can be saved with a Fixnum, and the result will be returned as a Fixnum object.

 Let's take a look at this code:

class Test
  # Define a variable named a with a value of 30 to the power of 2 minus 1
  a = 1073741823
  puts a.class
  # Define a variable named b with a power of 30
  b = 1073741824
  puts b.class
end
Result output:

Fixnum
Bignum
(1) Generally speaking, when a variable is defined to be an integer that is greater than or equal to the 30th power, the system automatically sets it to Bignum type; if it is less than this value, it is set to Fixnum type.

(2) An integer can be preceded by an optional symbol tag (used to specify whether it is positive or negative), an optional hexadecimal tag (0 for decimal, 0x for hexadecimal, and 0b for binary), followed by A string of digits in the corresponding base.

(3) If an underscore is used in the value, the underscore in the value is ignored.

(4) Note: The basic data type in Ruby is also an object. For example, in JS, we use Math.abs (5) to get the absolute value of a value. In Ruby, 5 is an object, and its absolute value is taken. The value is 5.abs (), which shows that Ruby is really object-oriented, everything is an object.

All integers are actually instances of the Fixnum or Bignum classes, so they can completely execute the methods of these two classes, such as iterators, such as times, upto, downto, and step, to replace the traditional for loop. Such as:

class Test
  # Iterative output three times
  3.times {print "X"}
  puts "\ n"
  # Iterate from 1 to 5
  1.upto (5) {| i | print i, ""}
  puts "\ n"
end
 (5) Get the corresponding integer value by adding "?" In front of the ASCII string. Note that because the question mark "?" Is followed by ASCII characters instead of strings, there is no need to use quotation marks and there can be multiple characters .

class Test
  puts? a
end
When you run it, you will be surprised to find that it actually outputs a. Later, you learned that this was used in Ruby 1.8, and it was used in the future.

class Test
  puts "a" .ord
  # Or
  puts? a.getbyte (0)
end
(5) By adding a question mark (?) In front of the string, and then taking getbyte (0), or by adding double quotes to the ASCII string, and then calling the ord method.

(6) When using scientific notation to represent a floating-point number, if the preceding part of e is an integer, either the decimal point is completely ignored, or 0 is added after the decimal point. As follows

class Test
  puts 5e2
  puts 5.0e2
end
If puts 5.e2 will definitely report an error, we mentioned earlier that the value is also an object. At this time, 5 will be used as the object, and then the e2 method is called, but if the method does not exist at all, an error will occur.

String
In the Ruby language, strings are instances of the String class, so any string variable or constant can call the instance method of the String class. The String class may be the largest built-in class in Ruby. It has more than 75 standard methods. It is enough to show that it is a very important class. In fact, in Ruby, single-quoted strings and double-quoted strings are essentially the same, but using double quotes will avoid many troubles caused by unnecessary operations.

class Test
  a = "Hello World"
  b = ‘Hello World’
  puts a == b
end
By printing out true, it is the same.

% Notation for strings
If we want a string to consist of multiple lines of strings, we can use the "%" notation. There are three ways of "%" notation:

(1)% / stuff /

(2)% Q / stuff /

(3)% q / stuff /

The above (1) and (2) are used in the same way, the slash represents the delimiter can also be a bracket.

Here's a demonstration with% Q and% q:

class Test
 # Define a global variable
  $ global = "Ruby"
  # Use% Q / stuff / to generate a multi-line string
  a =% Q /
  Hello, Ruby
  Ruby is Simple Language
  Ruby On Rais # {$ global} /
  # Use% q / stuff / to generate a multi-line string
  b =% q {
  Hello, Ruby
  Ruby is Simple Language
  Ruby On Rais # {$ global}}
  puts a
  puts b
end
  # {$ global} is used to replace the interpolation expression with the defined global variable. In the above, when using curly braces, the interpolation expression will be invalid.

Literals of multi-line strings
Ruby also provides a multi-line string representation, this syntax is also called Here Document. The most commonly used syntax format of Here Document is as follows:

class Test
  << Identifier
  stuff
Identifier
end
Let's take an example:

$ global = 123
# Define a string using Here Document
puts << Here
    This is a multi-line text content
    Use Here document syntax
    Sum = # {$ global + 1}
Here
The results print out:

    This is a multi-line text content
    Use Here document syntax
    Sum = 124
In general, we recommend writing the closing << at the top.

Array
Arrays in Ruby can be defined using a series of object references separated by commas in square brackets. The last comma in square brackets is ignored. As follows:

a = [4, 5, "Hello World"]
Note: The length of an array in the Ruby language is variable. When we specify the value of an array element in the middle, the value of the array element without a specified value before the element is nil.

An array in Ruby is an instance of the Array class. We can create an array by creating an instance of the Array class, as shown below:

my_array = Array.new
% Representation of array
The Ruby language can also convert a string containing multiple spaces into an array. Ruby treats spaces as array separators, and each space-separated substring is treated as an array element. If we need to convert a string of multiple spaces into an array, we need to use the "% w {...} or% W {...}" notation. These two methods have roughly the same function, but "% W { ...} "will make more additional substitutions.

$ global = 6
my_array =% w (Hellow Ruby On Rails,
      Ruby \ on \ Rails Is Funny! # {$ Global})
my_array2 =% W (Hellow Ruby On Rails,
      Ruby \ on \ Rails Is Funny! # {$ Global})
p my_array
p my_array2
Results print:

["Hellow", "Ruby", "On", "Rails,", "Ruby on Rails", "Is", "Funny!", "\ # {$ Global}"]
["Hellow", "Ruby", "On", "Rails,", "Ruby on Rails", "Is", "Funny!", "6"]
Array common methods
(1) Intercept the word array of the array

# Define a Range object
my_range = 1..9
# Convert a Range object into an array object
my_array = my_range.to_a
p my_array

# Truncate from the 3rd element of the array, intercept 2 elements in total
p my_array [2, 2]

# Intercept from the third element of the array, intercept to the fifth element, including the fifth element
p my_array [2..4]

# Intercept from the third element of the array, intercept to the fifth element, not including the fifth element
p my_array [2 ... 4]
Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4]
[3, 4, 5]
[3, 4]
(2) Assign values to multiple arrays

# Define a Range object
my_range = 1..9
# Convert a Range object into an array object
my_array = my_range.to_a

# Starting from the third element, replace 2 elements with a string element
my_array [2, 2] = "Ruby"
p my_array

# Starting from the third element, replace 1 element with 2 elements in total
my_array [2, 1] = ["Hello", "World"]
p my_array

# Replace the third and fourth elements with the three elements 7, 8, and 9
my_array [2..3] = [7, 8, 9]
p my_array
print out:

[1, 2, "Ruby", 5, 6, 7, 8, 9]
[1, 2, "Hello", "World", 5, 6, 7, 8, 9]
[1, 2, 7, 8, 9, 5, 6, 7, 8, 9]
Range
A range is a manifestation of multiple enumerations, and there are two forms for creating a range of this enumeration.

(1) Value 1 .. Value 2: Define a range from value 1 to value 2, including value 1 and value 2, and also the value between value 1 and value 2.

(2) Value 1 ... Value 2: Define a range from value 1 to value 2, including value 1 but excluding value 2, and also the value between value 1 and value 2.

Common methods
(1) to_a (): Convert the range into an array.

(2) include ()? (Targetvalue) === (tagetValue): Determine whether the range contains the ttageValue.

(3) min () / begin () / first (): Find the minimum value (first value) of the range.

(4) max () / end () / last (): Find the maximum value (last value) of the range.

The following are commonly used iterator methods:

(1) reject: convert the range into an array, and remove the elements that meet the conditions.

class Test
  # Use ... to define the range, then the range does not include the end point
  a = 2 ... 10
  # Convert the range into an array, and exclude the elements that do not meet the conditions
  print a.reject {| i | i <5}
  puts "\ n"
end
Prints out: [5, 6, 7, 8, 9]

(2) select: convert the range into an array, and select only the elements that meet the conditions.

class Test
  # Use ... to define the range, then the range does not include the end point
  a = 2 ... 10
  # Convert the range into an array, and select only the elements that meet the following conditions
  print a.select {| i | i <5}
  puts "\ n"
end
Prints out: [2, 3, 4]

(3) each: each element in the iteration range.

class Test
  # Use ... to define the range, then the range does not include the end point
  a = 2 ... 10
  # Use each to iterate over each element in the output range
  a.each do | ele |
    puts "when the current element:" + ele.to_s
  end
end
print out:

Current element time: 2
Current element time: 3
Current element time: 4
Current element time: 5
Current element time: 6
Current element time: 7
Current element time: 8
Current element time: 9
Conclusion
In this section we will go through and learn the basic data types, and in the next section we will go into expressions and statements.

The basic data types of Ruby (3)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.