CSC/ECE 517 Fall 2011/ch3 3h ss

From Expertiza_Wiki
Revision as of 22:45, 6 October 2011 by Sshanbh (talk | contribs) (→‎Ruby)
Jump to navigation Jump to search

Introduction

In any programming language, the data type refers to the class of data which contains specific type or range of values. Data types are used along with variables used in the program. The data type tells us what kind of values the variable can store, what is the range of the values and how much space the values take in memory etc.

The primitive data types refer to the built-in data types which are supported by the programming language. Often 'data types' and 'primitive data types' are used interchangeably.

Many object-oriented programming languages provide support for primitive data types while some object-oriented programming languages provide support for primitive objects along with primitive types. Primitive objects refer to the objects of built-in classes which provide the same functionality or rather more functionality than the primitive types. Some object-oriented programming languages provide support for only primitive objects.

The common built-in data types are integers, floating point numbers, characters, strings and booleans.

Different object-oriented programming languages implement these primitive data types and primitive objects in different manner.


Primitive objects in different OO languages

Ruby

Since Ruby is a pure object oriented language, everything in Ruby is an object. Hence, all primitive types such as integers, floating point numbers, strings, are objects of a built-in class. All integers are primitive objects of either class Fixnum or Bignum. e.g. 10.class returns Fixnum. This indicates that 10 is converted into an object of type Fixnum. A numeric literal with a decimal point and/or an exponent is a primitive object of Float. e.g. 7.45.class returns Float. This indicates that 7.45 is converted into an object of type Float. Single quoted literals and double quoted literals are primitive objects of String. e.g. 'hi'.class and "hello".class both return String. This indicates that 'hi' and "hello" are both converted into an object of type String.

Since all primitive types in Ruby are objects, we should be able to call methods of the Object class on them. Let us demonstarte the same for integer and float using the following example:

a=10 puts a.to_f b=20.5 puts b.to_i

Output: 10.0 20