Data types in Ruby represent different categories of data such as text, string, numbers, etc. Since Ruby is an object-oriented language, all its supported data types are implemented as classes.
Have a look at the various data types supported by Ruby in the illustration below:
A string is made up of multiple characters. They are defined by enclosing a set of characters within single (‘x’) or double (“x”) quotes.
puts "Hello World!"puts "I work at Educative"puts "My ID is 3110"
A number is a series of digits that use a dot as a decimal mark (where one is required). Integers and floats are the two main kinds of numbers; Ruby can handle them both.
my_int = 34my_flt = 3.142puts (my_flt * my_int)puts (my_flt + my_int)puts (my_flt / my_int)puts (my_int - my_flt)
The Boolean data type represents only one bit of information that says whether the value is true or false. A value of this data type is returned when two values are compared.
my_str_1 = "Hello"my_str_2 = "World"bool_1 = falsebool_2 = falseif my_str_1 == my_str_2bool_1 = trueputs "It is True!"elseputs "It is False!"endif my_str_1 == my_str_1bool_2 = trueputs "It is True!"elseputs "It is False!"end
An array can store multiple data items of all types. Items in an array are separated by a comma in-between them and enclosed within square brackets. The first item of the array has an index of .
my_array = [ "Apple", "Hi", 3.1242, true, 56, ]# printing all elements of the arraymy_array.each do |x|puts (x)end
A hash stores key-value pairs. Assigning a value to a key is done by using the =>
sign. Key-value pairs are separated by commas, and all the pairs are enclosed within curly braces.
Fruits_hash = { "Apple" => 10, "Banana" => 20, "Kiwi" => 30 }Fruits_hash.each do |key, value|print "Key: ", key, " | Value: ", value, "\n"end
Symbols are a lighter form of strings. They are preceded by a colon (:
), and used instead of strings because they take up less memory space and have a better performance.
my_symbols = {:ap => "Apple", :bn => "Banana", :mg => "Mango"}puts my_symbols[:ap]puts my_symbols[:bn]puts my_symbols[:mg]
Free Resources