DEV Community

Cover image for Built In Data Type in Ruby
Bhartee Rameshwar Sahare
Bhartee Rameshwar Sahare

Posted on

Built In Data Type in Ruby

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:

  1. A number is defined by a series of digits, using a dot as a decimal mark, and optionally an underscore as a thousands separator.
  2. 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
Enter fullscreen mode Exit fullscreen mode

String:

  1. The String, in programming languages, is text.
  2. Strings can be defined by enclosing any text with single or double quotes.
  3. 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
Enter fullscreen mode Exit fullscreen mode

True, False, and Nil:

  1. The object true represents “truth”, while false represents the opposite of it.
  2. The object nil represents “nothing”.

Symbols:

  1. Symbols are like strings, except they are code.
  2. A symbol is created by adding a colon in front of a word.
  3. A symbol is written like this:= :name
  4. Symbols are unique identifiers that are considered code, not data.
  5. 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
Enter fullscreen mode Exit fullscreen mode

Array and Hash Cover in Next Post......

Top comments (0)