Ruby Built-in Data type.
Bhartee Rameshwar Sahare
Posted on March 9, 2023
Float:
In Ruby, a float is a data type used to represent decimal numbers.
Floats are used to store numbers with a decimal point or numbers that are very large or very small.
Floats can also be created using exponential notation, where a number is represented as a base and an exponent.
The float is represented using a 64-bit format and can store numbers up to approximately 1.8 x 10³⁰⁸ with a precision of about 15 digits.
num = 2.05
=> 2.05
num = 2.5e-3
=> 0.0025
Date:
The date is a data type that represents dates.
The Date class is part of the Ruby standard library and provides a set of methods for working with dates.
Ruby using the Date.new method, specifying the year, month, and day as arguments.
We can also do arithmetic operations using date also.
To use the DateTime class in Ruby, you need to require it first by adding the following line at the beginning of your script.
date = DateTime.new(year, month, day)
require 'date'
=> true
date = Date.new(2023,02,05)
=> #<Date: 2023-02-05 ((2459981j,0s,0n),+0s,2299161j)>
year = date.year
=> 2023
month = date.month
=> 2
day = date.day
=> 5
new_date = date + 7
=> #<Date: 2023-02-12 ((2459988j,0s,0n),+0s,2299161j)>
DateTime:
DateTime is a datatype in Ruby. It is a built-in class in the Ruby Standard Library and provides methods for working with dates and times.
Ruby using the DateTime.new method, specifying the year, month, day, hour, minutes, second, offset
To use the DateTime class in Ruby, you need to require it first by adding the following line at the beginning of your script.
date_time = DateTime.new(year, month, day, hour, minute, second, offset)
date_time = DateTime.new(2023, 3, 9, 15, 30, 0, Rational(-5, 24))
month = date_time.month
=> 3
year = date_time.year
=> 2023
day = date_time.day
=> 9
hour = date_time.hour
=> 15
minute = date_time.minute
=> 30
sec = date_time.second
=> 0
offset = date_time.offset
=> (-5/24)
Text:
Text is a data type. The text data type stores any kind of text data.
It can contain both single-byte and multibyte characters that the locale supports.
The term simple large object refers to an instance of a text type.
Use Text for larger content, comments, content, and paragraphs.
The official rule is 255 for a string. So, if your string is more than 255 characters, go for text.
Blob:
Blob is used to represent binary data in the Ruby environment that is stored as a blob type in the database.
JSON:
The JSON data type is used to store JSON (JavaScript Object Notation) data.
require 'json'
=> true
json_string = '{"name": "John", "age": 30, "city": "New York"}'
=> "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}"
# The JSON.parse method is used to convert a JSON string into a Ruby data structure
json_data = JSON.parse(json_string)
=> {"name"=>"John", "age"=>30, "city"=>"New York"}
Array:
Arrays are like bags that contain things
An Array is an object that stores other objects.
The array is created by separating values by commas and enclosing this list with square brackets, such as:
[1, 2, 3]
Arrays are created by listing objects, separated by commas, and enclosed by square brackets.
Arrays can contain all kinds of things:
[“A string”, 1, true, :symbol, 2]
Arrays can contain all kinds of objects.
Arrays have a defined order and can store all kinds of objects.
# Punctuation (such as square brackets) has different meanings in different contexts.
# Arrays start with the index 0, not 1.
# Retrieving an element from an Array:
number = ["one", "two", "three"]
puts number[1]
=> two
# Appending an element to an Array:
number = ["one", "two", "three"]
number << "four"
puts number[3]
=> four
# Setting an element to a position:
number = ["one", "two", "three"]
number[3] = "four"
puts number[3]
=> four
# You could also overwrite existing elements the same way. For example this would set the word "uno" to the position 0 (i.e. overwrite "one"):
# Remark: there are no spaces inside the square brackets, and there’s one space after each comma.
number = ["one", "two", "three"]
number[0] = "eno"
puts number[0]
=> eno
# Missing elements:
# if we try to retrieve an element that does not exist
["one", "two", "three"]
=> ["one", "two", "three"]
words[3]
=> nil
#Things you can do with Arrays
# You can add Arrays:
[1, 2] + [3, 4]
=> [1, 2, 3, 4]
# Subtract them from each other:
[:one, :two, :three, :four] - [:three, :four]
=> [:one, :two]
# Multiply with a number:
["Ruby", "Monstas"] * 3
=> ["Ruby", "Monstas", "Ruby", "Monstas", "Ruby", "Monstas"]
# AND find the intersection:
[1, 2, 3] & [2, 3, 4]
=> [2, 3]
["Ruby", "Monstas"].first
=> "Ruby"
["Ruby", "Monstas"].last
=> "Monstas"
["Ruby", "Monstas"].length
=> 2
# the sort method is provided by the Array class and is used to sort the elements of an array in ascending order.
[3, 1, 2].sort
=> [1, 2, 3]
# remove the nil value
[1, nil, 2, 3, nil].compact
=> [1, 2, 3]
# is used to find the index of the first occurrence of a specified element in an array.
# If the element is not found, it returns nil.
[1, 2, 3].index(3)
=> 2
# it rotates the array by one position to the left.
# If a negative argument is provided, it rotates the array to the right.
# If the argument is greater than the length of the array, it performs multiple rotations.
[1, 2, 3, 4].rotate(2)
=> [3, 4, 1, 2]
# the transpose method works only on rectangular arrays, i.e., arrays where all rows have the same number of elements. If the array is not rectangular, transpose will raise an IndexError.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]].transpose
=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Hash:
Hashes are another very useful and widely used kind of thing that can be used to store other objects.
Real-time example:
Imagine a real dictionary that translates from English to German. When you look up the English word “hello” then you’ll find the German “Hallo”.When you look up “one” then you’ll find “eins”, and so on. The authors of this dictionary have assigned a German word (a value) to an English word (the key).
Hash assigns values to keys so that values can be looked up by their key.
A hash is created by listing key/value pairs, separated by hash rockets, and enclosed by curly braces.
# Define hash below ways:
{ one: "eins", two: "zwei", three: "drei" } # new syntax
{ 1 => "one", 2 => "two", 3 => "three" }
{ :one => "one", :two => "two", :three => "three" }
{ "weights" => ["pound", "kilogram"], "lengths" => ["meter", "mile"] }
{ :one => { :one => "one", :two => "two", :three => "three" } }
# Creating a Hash
dictionary = { "one" => "1", "two" => "2", "three" => "3" }
=> { "one" => "1", "two" => "2", "three" => "3" }
dictionary["zero"] = "null"
=> "null"
puts dictionary["zero"]
null
=> nil
# Merge the two hash:
number = { :one => "one", :two => "two", :three => "three" }.merge({ :four => 4 })
=> {:one=>"one", :two=>"two", :three=>"three", :four=>4}
# Fetch the hash:
number = { :one => "one", :two => "two", :three => "three" }
=> { :one => "one", :two => "two", :three => "three" }
number.fetch(:one)
=> "one"
number.fetch(:four)
=> # (irb):45:in `fetch': key not found: :four (KeyError)
# Returns an Array with all the keys and values:
number = { :one => "one", :two => "two", :three => "three" }
=> {:one=>"one", :two=>"two", :three=>"three"}
number.keys
=> [:one, :two, :three]
number.values
=> ["one", "two", "three"]
# length and size both tell how many key/value pairs the Hash has:
number = { :one => "one", :two => "two", :three => "three" }
=> {:one=>"one", :two=>"two", :three=>"three"}
number.size
=> 3
number.length
=> 3
Posted on March 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.