Ruby Data Types

In this chapter, we will introduce Ruby's basic data types.

The data types supported by Ruby include the basic Number, String, Ranges, Symbols, as well as the special values true, false, and nil, and two important data structures - Array and Hash.


Numeric Types (Number)

1. Integer

There are two types of integers. If within 31 bits (four bytes), it is a Fixnum instance. If it exceeds that, it is a Bignum instance.

The integer range is from -230to 230-1, and integers in this range are of classFixnumobjects. When the integer value is greater than or equal to 2 to the 30th power ( -262to 262-1), it will automatically be converted to Bignum type.

You can use an optional leading sign before the integer, an optional base indicator (0 for octal, 0x for hex, 0b for binary), followed by a series of digits. Underscore characters are ignored in the numeric string.

You can get the integer value of an ASCII character or an escape sequence marked with a question mark.

Example

123 #Fixnum decimal 1_234 #Fixnum decimal with underscores -500 #Negative Fixnum 0377 #Octal 0xff #Hexadecimal 0b1011 #Binary "a".ord #The character code of "a" ?\n #The code of the newline character (0x0a) 12345678901234567890 #Large number #Integer. The following are some integer literals. #Literal: Values that can be seen in code - numbers, boolean values, strings, etc. - are called literals. #Such as 0, 1_000_000, 0xa, etc. a1=0 #Integer with thousands separators a2=1_000_000 #Representation in other bases a3=0xa puts a1,a2 puts a3 #puts and print both print characters to the console, where puts includes a newline. =beginThis is a comment, called an embedded document comment, similar toC#the /**/ in =end

Floating-point Type

Ruby supports floating-point numbers. They are numbers with decimal fractions. Floating-point numbers are of classFloatobjects, and can be any of the following.

Example

Example

123.4 #Floating-point value 1.0e6 #Scientific notation 4E20 #Not required 4e+20 #Sign before the exponent #Floating-point Type f1=0.0 f2=2.1 f3=1000000.1 puts f3

Arithmetic Operations

Addition, subtraction, multiplication, and division operators: + - * /; exponent operator is **

The exponent need not be an integer, for example

Example

#Exponent arithmetic puts 2**(1/4) # The quotient of 1 and 4 is 0, then 2 to the 0th power is 1 puts 16**(1/4.0)#The quotient of 1 and 4.0 is 0.25 (one quarter), then take the fourth root.

String Type

A Ruby string is simply a sequence of 8-bit bytes, and they are objects of the String class.

Strings delimited by double quotes allow substitution and the use of backslash notations; strings delimited by single quotes do not allow substitution, and only allow two backslash notations: \\ and \'.

Example

#!/usr/bin/ruby -w puts 'escape using "\\"'; puts 'That\'s right';

Try it »

This will produce the following result:

escape using "\"
That's right

You can use the sequence#{ expr }to substitute the value of any Ruby expression into a string. Here, expr can be any Ruby expression.

Example

#!/usr/bin/ruby -w puts "Multiply: #{24*60*60}";

This will produce the following result:

相乘 : 86400

Example

#!/usr/bin/ruby -w name="Ruby" puts name puts "#{name+",ok"}"

The output result is:

Ruby
Ruby,ok

Backslash Notations

The following table lists the backslash notations supported by Ruby:

NotationsCharacter represented
\nNewline (0x0a)
\rCarriage return (0x0d)
\fForm feed (0x0c)
\bBackspace (0x08)
\aBell (0x07)
\eEscape (0x1b)
\sSpace (0x20)
\nnnOctal notation (n is 0-7)
\xnnHexadecimal notation (n is 0-9, a-f, or A-F)
\cx, \C-xControl-x
\M-xMeta-x (c | 0x80)
\M-\C-xMeta-Control-x
\xCharacter x

For more details about Ruby strings, please seeRuby String。

Arrays

Array literals are defined by comma-separated values within [], and also support range definitions.

  • (1) Arrays are accessed by index via []
  • (2) Insert, delete, and replace elements through assignment operations
  • (3) Use + and - to merge and remove elements, and the collection is returned as a new collection.
  • (4) The << sign appends elements to the original data.
  • (5) The * sign repeats array elements.
  • (6) The | and & symbols are used for union and intersection operations (pay attention to the order).

Example

#!/usr/bin/ruby ary = [ "fred", 10, 3.14, "This is a string", "last element", ] ary.each do |i| puts i end

Try it »

This will produce the following result:

fred
10
3.14
This is a string
last element

For more details about Ruby arrays, please seeRuby Array。

Hash Type

A Ruby hash is a series of key/value pairs placed inside braces, with keys and values separated by commas and the sequence =>. Trailing commas are ignored.

Example

Example

#!/usr/bin/ruby hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f } hsh.each do |key, value| print key, " is ", value, "\n" end

Try it »

This will produce the following result:

red is 3840
green is 240
blue is 15

For more details about Ruby hashes, please seeRuby Hash。

Range Type

A range represents an interval.

A range is represented by setting a start value and an end value. Ranges can be constructed using s..e and s...e, or via Range.new.

A range constructed with .. runs from the start value to the end value (inclusive). A range constructed with ... runs from the start value to the end value (exclusive). When used as an iterator, the range returns each value in the sequence.

The range (1..5) means it contains the values 1, 2, 3, 4, 5, and the range (1...5) means it contains the values 1, 2, 3, 4.

Example

#!/usr/bin/ruby (10..15).each do |n| print n, ' ' end

Try it »

This will produce the following result:

10 11 12 13 14 15

For more details about Ruby ranges, please seeRuby Range。

Other Extensions