Built-In Data Type in Ruby

BharteeTechRubyOnRails
2 min readMar 6, 2023

--

Data types are types of “things” that are mainly used to represent data, such as numbers, text, and other values.

We will discuss 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 thousand separators.
  2. Mathematical operations result in a floating point number except if all numbers used are integers.
0.1 + 2
=> 2.1
3.0/2
=> 1.5

String:

  1. 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

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. Technical differences:
# 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 will cover in the next post…..

https://medium.com/@learn-ror-with-bhartee-sahare/built-in-data-type-in-ruby-3e0f4398bfe9 Part2

--

--

BharteeTechRubyOnRails
BharteeTechRubyOnRails

Written by BharteeTechRubyOnRails

Ruby on Rails Developer || React Js || Rspec || Node Js

No responses yet