Data types are types of “things” that are mainly used to represent data, such as numbers, text, and other values.
We will discusss the following data types:
- Numbers
- Strings (texts)
- True, False, and Nil
- Symbols
- Arrays
- Hashes
Number:
- A number is defined by a series of digits, using a dot as a decimal mark, and optionally an underscore as a thousands separator.
- Mathematical operations result in a floating point number except if all number s used are integer numbers.
# 0.1 + 2
# => 2.1
# 3.0/2
# => 1.5
String:
- The String, in programming languages, is text.
- Strings can be defined by enclosing any text with single or double quotes.
- These last few examples are examples of “calling methods on objects that are Strings”. Methods are “behaviour” that objects are capable of.
"This is one String!"
'And this is another one.'
# Here are a few things you can do with Strings:
"bhartee" + "sahare"
=> "bharteesahare"
"hi" + "hello" + "hey"
=> "hihellohey"
"hey" * 2
=> "heyhey"
"1"+"1"+"1"
=> "111"
"1"* 5
=> "11111"
"hello".upcase
=> "HELLO"
"hello".capitalize
=> "Hello"
"hello".reverse
=> "olleh"
"hello".length
=> 5
True, False, and Nil:
- The object true represents “truth”, while false represents the opposite of it.
- The object nil represents “nothing”.
Symbols:
- Symbols are like strings, except they are code.
- A symbol is created by adding a colon in front of a word.
- A symbol is written like this:= :name
- Symbols are unique identifiers that are considered code, not data.
- Symbols are a special, limited variation of Strings. The technical difference:
# even though the 3 Strings created are exactly the same, every new String created has a different object_id: They’re actually different objects, even though they contain the same text.
"a".object_id
=> 460
"a".object_id
=> 480
"a".object_id
=> 500
We now get the same object_id for each of the Symbols, meaning they’re referring to the exact same object.
:test.object_id
=> 380188
3.0.0 :002 > :test.object_id
=> 380188
3.0.0 :003 > :test.object_id
=> 380188
Array and Hash Cover in Next Post......
Top comments (0)