Ruby. Peter Wilhelmsson

Size: px
Start display at page:

Download "Ruby. Peter Wilhelmsson"

Transcription

1 Mathias Alexandersson Ruby Peter Wilhelmsson Sven Andersson Abstract Ruby is a pure object oriented scripting language. It is an easy to learn, everyday language that is mainly used for small programs. People have put a lot of energy into the syntax to keep it easy to read and understandable. Ruby is heavily based on Perl and a little on Python. It is also somewhat based on Smalltalk since that is a pure object oriented language. The syntax is inspired by Ada. Ruby provides possibilities to ext its use via several other major programming languages and toolkits. There is also an extensive standard library that ints to cover all the basic uses for scripting.

2 Introduction Because Ruby is relatively unknown outside of Japan, this article aims to introduce the Ruby language, its uses and how well it performs against other languages. The aim for the parts describing the language itself is to find the specific features that are not supplied with your everyday programming language. The article gives a brief insight into the history of ruby, its standard library and its nuts and bolts. Performance evaluation towards compiled languages and its major competitor Python will also be covered. Thoughts and history behind ruby Ruby was created by Yukihiro Matsumoto from Japan. In 1993 Matsumoto had been a long time fan of object-oriented programming and in the later years he had become impressed by the power and the possibility that scripting languages provided so he wanted to have a language that where both scripting and object-oriented. He found Perl 5, which had not been released yet. Perl 5 was going to implement object-oriented features but Matsumoto felt that it was not enough. He also came across Python, which was an interpretive, object-oriented language. But Matsumoto didn t feel that is was a scripting language and in addition it was a hybrid language of procedural and objectoriented programming [6,7]. I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. That s why I decided to design my own language. - Yukihiro Matsumoto Matsumoto started to develop Ruby on February 24, The first alpha version where released in December Even though Matsumoto had some complains on Perl and Python he liked some parts of them enough to incorporate them in Ruby. Ruby s class library is an object-oriented reorganisation of Perl functionality. He also used some Smalltalk and Lisp. From Python he used far less then he used from Perl but for example he used the exception names and he learned a lot from its code. He worked alone developing the language until 1996 when the Ruby community started to form. Matsumoto is still doing most of the work alone but many people are helping out with fixes and patches. It is still mainly the Japanese open source community that helps but since Ruby is starting to get some fans in other countries, more and more people is trying to make Ruby a better language. The name Ruby, have no hidden meaning. It s inspired by the name Perl, which is also a valuable thing, and was from the beginning just a temporary name but it later became the official name of the language. I believe people want to express themselves when they program. They don t want to fight with the language. Programming languages must feel natural to programmers. I tried to make people enjoy programming and concentrate on the fun and creative part of programming when they use Ruby. - Yukihiro Matsumoto

3 Even though Ruby is very successful in Japan it is not very well known in Europe and U.S. The reason for that is probably that the first English documentation where released in 1997 and there is still a lack of English documentation. But is has become a lot better the last years. It was not until 2000 that people started to use it in U.S. At the moment Ruby have the version number The plans of the future for Matsumoto, is to rewrite the interpreter for ruby 2.0. It will become easier to embed, thread-safe and faster and it will use a bytecode engine. This will probably take years to implement since Matsumoto still put down a lot of time to maintaining the current version. Language features Class definition The representation of a Ruby object contains three components. First a set of flags determining meta status for the object, the instance variables and a reference to an instance of the class Class. The Class object contains the references to methods and a reference to the objects super class. When a method is called it first looks in the objects references to methods, if not found it looks for the method in the super class. If no method is found an exception is thrown. class Foo def = tobebar def amethod puts bar The def tells the that a method is defined, that the definition of the block s. initialize is the constructor of the class. is used to define instance variables The classes in Ruby are not constructed during compile time like in C++ and java. They are built during execution as they appear in the code while interpreted.

4 Inheritance Ruby does not support multiple inheritances. A class can only have one super class unlike in C++ where a class can have several super classes. However there is a feature in Ruby that allows for similar behaviour and it is called mixin. Ex. class Foo < Bar def initialize(foobar) super(foobar) Foo < Bar defines Foo to be a sub class of Bar. The call to super in Foo calls Bar constructor. Overloading In Ruby operators are the same as method calls. This lets us overload operators in the same way as overloading a method. To overload a method just make a new definition in the subclass. Ex. class Foo attr_accessor :value def <=> other.value The example demonstrates how the class ( Foo) overloads the operator ( <=>), which covers all comparison operators. Exceptions Exceptions in Ruby have no surprises to it. There is an exception class that can be thrown, catched and handled. The garbage collection Ruby implements a mark and sweep garbage collection. The mark and sweep garbage collection works in two phases. First it works its way through the objects marking every object that is referred to. Second it removes all the non-marked objects. This concept is the most widely used for implementing a garbage collection.

5 Methods Methods are simply a set of expressions that returns a value. To define a method the keyword def is used. The naming convension in Ruby states that method names should begin with a lowercase letter, although they are not required to do so. However, if the name should begin with an uppercase letter, the parser can interpret the method name to be a constant, and misinterpret the expression. The naming convension also says that methods that are queries, i.e. returning either true or false, should with a question mark (?). Methods that modifies the instance in some way should be ed with an exclamation mark (!). All arguments to the method are declared as a list of local variables within parentheses that follows the name. These arguments can be given a default value by simply using the assignment operator. It is possible to define methods with variable-length arguments, by putting an asterisk in front of the last argument. That argument will then be a list of all the remaining parameters. The body of the method can contain all normal Ruby expressions, except definition of classes, modules and instance variables. The return value of a method is the value of the last executed expression in the method, or it can be explicitly returned using the return expression. Modules Modules in Ruby provides a tool to group similar functionality to improve the reusability and structure of the code. It provides name spacing for the language. Actually... the Module class of module is the superclass of the Class class of class. Got that? - Ruby user s guide module Foo def Bar puts "FooBar" Declaring a module require Foo Foo.Bar() Using a module

6 Mixin Including Modules can be included into classes and other modules. This is called mixin in Ruby. By doing this classes use the modules methods as it was its own member methods and a class can include more than one module. A class can include several modules which gives the functionality of multiple inheritance. class Bar include Foo Bar includes the module Foo. When a module is included to a class the class gets a reference to the module. There will only be one instance of the module even if several classes include it. Modules can have instance variables. When a class includes a module with instance variables these variables are created for the object to use as its own. There is no sharing of these variables among the objects that includes the module. Exting You can also mix modules with a specific object with the Object.ext method. This will give the object the methods of module, if you do it to a class definition object you add the modules methods as class methods. Assignment Assignment sets the variable or attribute on the left side to the value of the expression on the right side. The assignment statment then return the value that was assigned, which enables chaining of assignments [1]. Assignments in ruby can be divided into two different forms: Assignments of variables and constants, and assignments to object attributes. Because the instance variables is only accessible from within the class itself, assignments to these from the outside is done through calling a method that sets the value. These methods are called attribute accessors. Accessor methods can be automatically created dynamically by using the attr accessor-function in Method method [1]. Parallel assignment Assignment in ruby is parallel, meaning that the values that are to be assigned are not affected by the assignment itself. All the values on the right side is evaluated (in the order that they appear) before the values are assigned to the left side. If there is more values on the left side than the right, the overlapping variables will be set to nil. a, b = b, a Swapping two values.

7 Basic types Numbers Ruby uses both integers and floating point numbers. Integers are divided into different classes: Fixnum for integers in the normal range, and Bignum for arbitrary numbers [4]. Fixnum Fixnum is used to hold integers that can be represented in native machine code minus one bit (usually -230 to 230 or -262 to 262), and it represents its value in binary form. Operation on a Fixnum that results in a value that exceeds the range, it is converted into a Bignum. This is done transparently, and Ruby automatically manages the conversions. The Fixnum object has a immediate value [4]. Bignum Bignum holds integers that are outside of the range of Fixnum. It is implemented as a set of short-integers, with a variable length. If an operation on a Bignum results in a value within the range of the Fixnum, it is automatically converted to a Fixnum. When using bit-operations on a Bignum it is treated as a string of bits with an infinite length. Bignum does not have immediate values like the Fixnum [4]. Float Float objects are used to hold real numbers. These are stored using the machine s native double-precision floating point representation [4]. Strings In Ruby, strings are objects of the class String, and are represented as sequences of 8-bit bytes. Though they are normally used to hold characters, they are not required to, and can be used to store binary data as well. Creating strings The usual way of creating string is by using string literals, sequences of characters between delimiters. Escape-sequences can be used in these string literals to represent special non-printable characters, such as line feeds, tabs etc. Ruby supplies two kinds of delimiters for the string literals: single and double quotes. The single quote only performs two substitutions. Two consecutive backslashes (\\) is substituted by a single backslash, and a backslash followed by a single quote (\ ) is substituted by a single quote. The double quotes offer more substitutions, such as the newline character "\n". In addition to the to the escape characters, Ruby can also substitute values of expressions in strings. This is done by using the sequence #expr expression. The expression can be a single variable.

8 string with single quotes "string with substitution #(value)" Strings can also be created using %q and %Q in the code. %q is for singlequoted strings and %Q for double-quoted. The character that follows the q or Q is the delimiter. If it is an opening parenthesis, bracket, brace or <, the string is read until the matching close-symbol is found. Otherwise the string is read until the next occurrence of the delimiter is found. %q/a single quoted string/ %Q/a double quoted string/ Finally there is another way of creating strings, here documents. These are used for long string literals. Here documents are constructed by using the sequence <<terminating string and consists of all lines in the code up to a line with only the terminator is found. Normally the terminator has to start at the first column, but if it is prefixed with a - (minus) it can be indented [1]. Ranges astring = <<END_OF_STRING The string will contain all lines up to one ing with the text that followed the << END_OF_STRING Ranges are used to represent intervals, sequences of objects with a start and an. The objects in the range can be of any type of object, as long as it responds to the succ-method, which returns the next object in the sequence, and must be comparable using the standard comparison operator ( <=> ). Ranges are created using the.. and... operators with the syntax start.. or start... The two-dot version of the operator includes the object in the range, whereas the three-dot version does not [4]. (1..5).to-a >> [ 1, 2, 3, 4, 5 ] ("bar".."bat").to-a >> ["bar", "bas", "bat"] Ranges are not stored as lists of objects, but as a Range object that has a description of the range. Ranges can also be used as conditions [1]. while gets print if /start/..// Ranges can also be used as intervals, or specifically to test if a value is in the range of an interval. This is done using the === operator. (1..10) === 5 >> true (1...4) === 4 >> false

9 Regular expressions Ruby has a built-in support for regular expressions. These are stored as objects of the class Regexp. Regular expression ca be created using the Regexp.new constructor or one of the two literals: // and %r{} [4]. Regular expressions can then be used to match against strings using the match operators: = for a positive match, i.e. the string matches the pattern, or!, for negative matches, ie the string does not match the pattern. The operator can also be used to match patterns from other regular expressions. a = Regexp.new( ^\s*[a-z] ) b = /^\s*[a-z]/ c = %r{^\s*[a-z]} The result of an unsuccessful match (ie a string that did not match a pattern) is nil. The result of a successful match is an object of the class MatchData, witch contains information about the match. The result of the match is also stored in the thread specific variable $~ [1]. Arrays Arrays are collection of references to objects, where every reference is positioned at a specific position, identified as a non-negative integer, in the array. The positions in the array is zero based, i.e. the first element is located on position 0. The references can be accessed using the [] operator with the position of the desired reference. By calling it with a negative number, the indexes is counted backwards from the. Should the specified index exceed the length of the array, nil is returned. To assign the references the []= operator is used. If a reference at an index that exceeds the length of the array is assigned, the array is resized to contain the new index. All references between the old of the array and the new length are set to nil. Arrays can also be indexed with a pair of numbers to return a sub section as a new array, starting at the position given by the first argument, and containing the number of elements as given by the second argument, or with the rest of the numbers in the array, if there are not enough elements in the array. Arrays can be created in several ways. An array can be created using the constructor Array.new. It is possible to s the initial length of the array as an argument. Another way to create arrays is to assign them directly in the code simply by stating the desired objects in a comma-separated list within angle brackets. Ranges can also be used to create arrays [4]. Hashes Hashes (also known as associative arrays) are very similar to arrays, except instead of using number to index, the references are indexed using any type of object. When a value is to be stored, two objects are required: a key and a value. The key will then be used to access the value from the hash.

10 The use of singletons in Ruby and Static members Singleton The design pattern singleton describes a way to make sure there is only one instance of a class. Ruby provides the module Singleton for this. The module Singleton prevents the class from being duplicated and makes sure that the singleton behaviour is preserved while inherited. The reason why singletons are presented here is because they need to be understood before explaining how static members are implemented in Ruby [1]. Unnamed classes Ruby provides the class << object statement which creates a singleton that inherits the objects class and the object s up with unique functionality [1]. foo = "bar" class << foo def putbar puts "bar" This will give foo, that is an instance of String, the method putbar. If this is done several times to the same object the singleton class will only be exted, there will not be a chain of superclasses to the object. Class methods By using the class << object on a object of the class Class gives another feature, namely the implementation of class variables and class methods. A Class method or singleton method, also called static method, is a method that does not need an instance of the class to be made, it can be called anyway. Ex. Class Foo class << Foo def theclassmethod puts "Foo" class << classname creates a singleton class that inherits the class Class, i.e. the class that holds the representation of classes. This is just one way to do this as ruby is flooded with syntactic sugar. Class variables Class hold the features as a class method with the obvious difference that they are variables and the less obvious that they can only be private. A class variable is created by instead in front of the name.

11 Unnamed functions and iterators Ruby provides two kinds of unnamed functions, blocks and closures. Blocks and closures are first class values, i.e. they can be passed as parameters to a method. Blocks and closures are similar to each other but their uses are different. Blocks and iterators A block itself is a nameless function that can be passed with a method call. All methods can receive a block and it is possible to check if a block was passed with the Kernel::block given? method. The method then invokes the code with the keyword yield. def foo yield foo() { puts "bar" } Puts bar is passed within the block and will be executed by yield in foo Blocks can only appear after a method call. When the interpreter encounters a block it does not execute the statements. The statements are saved with their context and held for the later use. This means that local variables used in blocks can be used even if they are outside the scope. An example of one way to take advantage of blocks is to pass them to a method that open files. The method open the file, applies the block code on the file content and closes the file. This way is supplied within the Ruby standard library. When used in combination with the iterators in Ruby the block feature shows its true use in Ruby. Iterators in Ruby are different from the once seen in Java and C++. Rather than having a collection return an iterator you pass a block, with the desired operation for each element, to the collections iterator. Closure Closure is another version of unnamed functions and can be passed as blocks to methods. The difference is that a closure is an object containing a block. Ruby has support for true closure, they remember their context the same way as blocks. So variables from outside the scope of the closure execution will still be available. This even if the closure was defined with instance variables of a deleted class [1,8]. Actually, to tell the truth, the first reason is to respect the history of Lisp. Lisp provided real closures, and I wanted to follow that. - Yukihiro Matsumoto

12 Threads In Ruby threads are handled as objects like everything else. The threads them self are held completely within the Ruby process and interpretator, this gives portability. Drawbacks of this approach are, since the thread are not native, possible starvation of low priority threads, deadlocks are fatal to the application and if a thread fails the whole application will fail to [1]. When creating a new thread the code block to be run is passed and any variables declared within that code is accessible to the thread. The created thread can access any public variables. Synchronizing threads Ruby provides a class for mutual exclusion, which is used to prevent a thread from being pre-empted when it may lead to corruption of data. The class Mutex does this. Mutex is implemented as a simple semaphore. A crude way to secure a thread from being pre-empted is to toggle a flag called Thread.critical to true. If the flag is true no other thread may pre-empt the running thread. Condition variables can be used when a thread needs to wait for a resource. A condition variable is implemented as a semaphore that is attached to a critical section. It makes the thread wait for a signal before entering the critical section [1]. Accessing and manipulating threads Threads can be started, stopped and unscheduled by methods provided in the Class Thread. A thread can be assigned to wait for other threads to terminate, i.e. the main thread can be kept from terminating while child threads execute since a terminated main thread will terminate all child threads. Methods for listing and querying thread status are also implemented in Thread. Local variables in the thread can be accessed as if the thread was a hash table [1]. Portability Ruby s Portability for Microsoft Windows. Ruby was written in Unix, that means that it was naturally written for POSIX environment and it can make use of all the system calls and libraries that Unixprogrammers are familiar with. Beside Unix, Ruby can also be run on other platforms such as DOS, Windows, Macintosh and BeOS. We chose to concentrate on how to get it to work on Windows since that is the most common OS in Sweden today. The best known port to windows is cygwin32. It s widely spread and is available on the Web as a precompiled binary. Beside Cygwin there exists at least three other possibilities for Ruby to work under windows, MinGW, Mswin and Native VC++.

13 Cygwin An advantage with Cygwin is that extension modules written in Unix probably require very little or no porting. There have been some problem with the old cygwin ports on Windows XP. MinGW Using Windows runtime libraries, no third part stuff. People that are already familiar with gcc and other Unix development tools should find it easy to learn how to use MinGW. Mswin Mswin32 does not rely on Cygwin. A downside is that it is only available as source code. It seems like very few actually are using Mswin anymore. Native VC++ This is the most used port for Ruby. Easy to write exted libraries with DirectX, COM etc. with native headers and libraries. Since this is the most used port, there exist more extension writers etc. The I/O performance was terrible but this has been fixed in the version of Ruby. The biggest disadvantage is perhaps that VC++ isn t free this is not however such a big problem, since VC++ is a very common tool. Exting Ruby with C It is quite easy to ext Ruby with features written in C since Ruby itself is written in C We can start to take a look at how to represent and access Ruby data types in from C. Everything in Ruby are objects and all variables are references to objects. This means that all Ruby variables in C is VALUE, these are either pointers to a Ruby object or immediate value (Fixnum) To implement a Ruby object in C, allocate a structure in the memory that contains at table of instance variables and information of the class. The class is another object that is represented as an allocated structure that contains a table of method defined for the class. This is the big picture of Ruby in C [1]. Ruby Variables as pointers As previously stated Ruby variables is seen as VALUE in C. These are pointers to defined Ruby object structures, they can t be pointers to a arbitrary structure. You can check what type of structure that is used for a VALUE the macro TYPE(obj), that will return a constant representing the C type of the given object, can be used. Ex. T OBJECT, T STRING. The type is the C structure that represents a particular built-in type. The class of an object is something different. The class objects for the built-in classes are stored in global C variables.

14 To get access to members from these C structures you have to cast the generic VALUE to the proper structure type. ruby.h contains a number of macros that helps dereference structure members [1]. VALUE str, arr; RSTRING(str)->len -> length of the Ruby string RSTRING(str)->ptr -> pointer to string storage RARRAY(arr)->len -> length of the Ruby array RARRAY(arr)->capa -> capacity of the Ruby array RARRAY(arr)->ptr -> pointer to array storage Variables as an Immediate Object Immediate values are not pointers but they are stored directly in VALUE; Fixnum, Symbol, true, false and nil. The Fixnum values are stored as 31-bit numbers and shifting the numbers left 1 bit. Then they set the least significant bit to 1. This means that it is possible to see if it is of the type Fixnum just by using a simple bit test. The other immediate values are represented as constants; Qtrue, Qfalse, Qnil. You test VALUE directly or use some of the already existing conversion macros to get access to the immediate objects. C and Ruby coding To write Ruby program almost directly in C, the same methods and the same logic but with some different syntax is used. One important thing to remember is that all the C functions that is callable from Ruby must return a VALUE, at least Qnil. We can use the C code in Ruby just by requiring it dynamically at runtime require "code/ext/test" t = Test.new t.add("kalle") To share a global variable between Ruby and C, the Ruby object must first be created in the C-code and then bound to a global variable in Ruby. VALUE cars_list; cars_list = rb_ary_new(); rb_define_variable("$cars", &cars_list); rb_ary_push(hardware_list, rb_str_new2("volvo")); rb_ary_push(hardware_list, rb_str_new2("ford")); rb_ary_push(hardware_list, rb_str_new2("opel")); The global variable cars are bound to cars list. cars is the variable that Ruby then uses. The $ is optional but it helps to clarify that cars is an global variable [1].

15 Wrapping To handle a C-structure as a Ruby object, it is wraped in an internal Ruby class called DATA (type T DATA). There are two macros to do this wrapping. VALUE Data_Wrap_Struct(VALUE class, void (*mark)(), void (*free)(), void *ptr") *ptr is the data type that we wrap. We return a VALUE pointer to a Ruby object. VALUE Data_Make_Struct(VALUE class, c-type, void (*mark)(), void (*free)(), c-type *") Allocates a structure of the type then use the Data Wrap Struct. c-type is the name of the C data type that you are wrapping, not a variable of that type Memory allocation To allocate memory that is not used to store objects. It may be for example, a gigantic bitmap, an image or some structures that Ruby does not use directly. If you want the garbage collector work properly you should use some of the memory allocation routines below. These routines do a little bit more than the standard malloc. An example is the ALLOC N that is it cannot allocate the desired amount of memory it will use the garbage collector to try and reclaim some space. If it can t reclaim the full amount of memory or it s simply not enough memory it will raise a NoMemError exception [1]. type * ALLOC\_N(c-type n ), Allocates n c-type objects, c-type is the literal name of the c-type, not a variable type * ALLOC(c-type") Allocates only one c-type and give the results as a pointer of that type REALLOC\_N(var c-type, n ), Reallocates n c-types and assigns the result to a pointer to a c-type type * ALLOCA\_N(c-type n ), Allocates for n c-type objects on the stack. This memory will automatically be freed when the function that invokes ALLOCA N returns. How to use the extension To use C-code in Ruby, it is needed to be compiled so that Ruby can use it. There are two alternatives how to use the extension, either a shared object, which is dynamically loaded, or to statically link the extension into the main Ruby interpreter itself.

16 Ruby interpreter in C It is also possible to make use of Ruby in C-code. To use Ruby, the ruby.h should be included and the function ruby init() called to initiate the interpreter. Ruby files can then be loaded using the rb load file("ruby file.rb") method, and executed with the ruby run() method [1]. Ruby and other languages We have been concentrating on Ruby and C because it is possible to bridge the language to C then you can ext it to all other languages that also can be bridges to C. It is also possible to can ext without using C, instead you use a middleware such as CORBA or COM. Ruby and the Web Ruby is quite useful when it comes to the Internet. It can be used used for common things such as CGI programming or as a replacement for PHP. CGI Of course it is possible to use Ruby s regular expressions to parse incoming query strings but this seems like a lot of extra work. Instead you can use the class CGI The class CGI provides support for writing CGI scripts. You can use it to manipulate forms, cookies, environment and so on. CGI contains many methods used to create HTML. For every HTML-tag there exist one method. To enable these methods you must make a CGI object by calling CGI.new( HTML version). The methods that parse to HTML, in class CGI take their contents as code blocks. These code blocks returns string. Which is used as the contents of the tags. To create a cookie objects that includes a number of values and other interesting stuff and sent down to the browser. You just need to set a cookie header in the cal of cgi.out. cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC"); cgi = CGI.new("html3") cgi.out( "cookie" => [cookie] ){ cgi.html{"html content here"} } It is also possible to use sessions, it provides a persistent state for the web surfer. Sessions uses cookies but at a higher level of abstraction. Ruby in HTML Besided from generate HTML code with the assistance of Ruby, it is also possible to embed Ruby in the HTML code. To embed Ruby in HTML you need a package that is known as eruby. It exist several different implementation of eruby for example eruby and erb. The most common one is eruby, written by Shugo Maeda. Embedding Ruby in HTML gives a tool equivalent to ASP, JSP or PHP. But it uses Ruby with all the possibilities in this language [1].

17 eruby acts like a filter. It passes through any text in the file with the exceptions of: <% ruby code %> The code between the delimiters is interpreted as Ruby code and replaced with its output. <\%= ruby expression %> The Ruby expression between the delimiters is replaced with its value. <\%# ruby code %> The Ruby code between the delimiters is interpreted as a comment. Ruby GUI extensions In Ruby s application archive there exist several extensions that provide Ruby with graphical user interface. Some of the extensions are, Tcl/Tk, GTK and OpenGL. The Tk extension is included in the main distribution and works on Unix and Windows systems. The way Ruby use Tk is similar to the way Tk is used in Perl. Tk This is perhaps the most common tool to use when create a graphic user interface in Ruby. Tk uses the composition model. This means that it creates a container widget and then create other widgets that populate the container, these can also have widgets populating themselves. When creating a GUI in Tk, start with creating a container widget and then the buttons, labels and other thing that you want to display. To invoke the GUI you call tk.mainloop and the Tk engine takes control of the program, displaying the widgets and responding to GUI events [1]. Performance Ruby is not focusing to be a high performance language but rather easy to use programming language. The reason that the people that develop Ruby does not focus on the performance part is that they think that the machines is developing in such a speed that they will handle the programs even though they aren t optimised. But the humans that are programming aren t evolving and so the important part of programming language is that it s concentrating on the people instead of the machines. One of the best known comparisons between different languages including Ruby is The Great Computer Language Shootout done by Doug Bagley. These tests include many languages, among them Python and Perl. It s important to know that these tests have been made for fun and should not be considered as the absolute truth. Some of the tests are object instances, working with hash-tables, arrays, lists, strings, exceptions and randomising. These test shows that Ruby are only slightly below Python and Perl in performance. We also included C++ to show the difference between a scripting object-oriented language and a compiling object-oriented language

18 Table 1 shows how the different languages ranked between each others deping on how well they handle different tasks [10]. Ruby Python C++ Test CPU MEM LOC CPU MEM LOC CPU MEM LOC Array Access 3 2 1* 2 3 1* Count Lines/Words/Chars String Concatenation Word Frequency Hello World 2 2 1* 3 3 1* Exceptions Echo Client/Server List Processing Matrix Multiplication Method Calls Object Instantiation Random Number Generator CPU: how CPU efficient it is. Mem: Memory efficiency. LOC: Lines Of Code. The * is if they are equally good. Table 1: Performance comparison between Ruby, Perl and C++ Ruby and Python Since Python also calls itself object oriented scripting language we want to see what difference there is between Ruby and Python. Python and Ruby both borrows a lot from other scripting languages such as Perl. The first thing that differs is that Python starts out as a procedural language and adds object oriented features while Ruby have the object oriented features implemented from the beginning. Ruby is a pure object oriented language that allows the code to look like procedural language [2]. Object oriented There have been some debating on how object oriented python is and one thing that people use as an argument to say that it s not as object oriented as Ruby is that there exist a lot of built in functionality that is implemented as functions. Ruby have no built in types, for examples int. There exist no functions in Ruby, only methods. Inheritance Python allows multiple inheritances while Ruby only accept single. Ruby use the concept of modules to give the same functionality as the multiple inheritance.

19 Access Ruby is like java in its type of access to the elements of a class, it support private, protected and public. All methods are public by default and all instance variables are private. Python had initially no access protection. They added a mechanism called name mangling which rename the class members starting with two underscores ( ). Now the members outside the class cannot get the same mangle names simply by referring to name Python does not support the notation of protected class members at all. Dynamic typing In both Ruby and python all types are dynamic. This mean that you do not need to set the type of the variables when you initiate them. Syntax The Syntax of Ruby is simpler and more readable but Python have a slightly more compressed code, which means that it needs less code to write an equal program. Easy to learn Both Ruby and Python is known to be languages that you don t need a lot of knowledge to start to write your first programs in. they are also good to write simple prototypes in since they are so simple. High-Order functions Both Ruby and Python features high-order functions. Ruby use procedure objects and python use lambda keyword. Ruby use the call method and Python use a anonymous function object Ruby p = proc do x print "hello ", x,"\\n" p.call "Karl" Python p = lambda x: print "hello", x p("kalle!") Iterators and list comprehension Ruby supports iterators that goes trough every element of any container class. Python use list comprehension to get a similar effect.

20 Garbage collector Ruby use a mark and sweep garbage collector and python use a reference counting garbage collector. Threading Ruby has no native thread support. While granting platform indepence it has several setbacks accociated with threads not being scheduled by the operative system, Ruby threads are also very slow. Python on the other hand provides access to several platforms thread capability through its api. However native thread support for Ruby will be implemented in the next major Ruby release. Exceptions There is no difference between Ruby and python when it comes to exceptions. Both of them support exceptions in the same way as java uses it. Libraries Both have large built in libraries Portability They work on most common platforms like Linux, Windows, MS-DOS, Unix, Mac, BeOS, OS/2 and some more. Summary Overall there is not much that differs between the two languages. Though Ruby have some cleaner syntax and is a bit more object oriented and have more features then Python. Python have the advantage of being older and have a lot more documentation then Ruby. Support When it comes to support the opinions drifts apart, some people think that Open Source is not as good because they don t have the same tech support as commercial products have. This may be true but people that use Open Source t to be more willing to share their knowledge with others. This is the case with Ruby. People work together to improve ruby and help other that is new to the language. Even though the language syntax does not change a lot over time there is new features added now and then, by people that want to improve the language. This have a negative side also, the documentation have a tency to fall behind since most people are more interested in coding that in document what they have done. The Ruby community is pretty organised with mailing lists and newsgroups. Also Matsumoto participate in these discussions from time to time. The most

21 widely used English mailing list is Ruby-talk. All post that is made at Ruby s own newsgroup (comp.lang.ruby) is archived and mirrored to the Ruby-talk mailing list. Ruby s official homepage is You find a complete online reference to Ruby s built-in classes and modules at [3,6]. Conclusion When we have looked at some of the pieces of Ruby and what possibilities it have. We came to the conclusion that it is a language that perhaps is not the best when it comes to writing fast and efficient programs but it is truly a language that has the focus on the programmers. It is easy to get started and a lot of simple methods that helps the programmer to write small programs in a small amount of time. Ruby is also a language where it is quite easy to read already written code and understand it. The fact that it is purely object oriented is a good feature because that helps to get a good structure and view of the code. It is also easy to write extensions for existing programs. The biggest disadvantage that ruby has is, as mentioned earlier, is the performance. But that is not unique problem for Ruby, most scripting languages are low performance languages. This is not a big problem though since scripting languages are mostly used to write small programs or user interfaces. Another disadvantage is the lack of documentation and books in english.

22 References [1] Programming Ruby - The Pragmatic Programmer s Guide D. Thomas and A. Hunt Addison-Wesley, UK, , ISBN [2] A comparison of object oriented scripting language: Python and Ruby K. D. and D. Grimes [3] Ruby Home Page [4] Ruby class reference [5] The Programming Language Ruby Y. Matsumoto [6] RubyCentral [7] RubyGarden.org [8] Blocks and Closures in Ruby B. Venners [9] Ruby user s guide Y. Matsumoto slagell/ruby/ [10] The Great Computer Language Shootout D. Bagley doug/shootout/

Principles of Programming Languages. Objective-C. Joris Kluivers

Principles of Programming Languages. Objective-C. Joris Kluivers Principles of Programming Languages Objective-C Joris Kluivers joris.kluivers@gmail.com History... 3 NeXT... 3 Language Syntax... 4 Defining a new class... 4 Object identifiers... 5 Sending messages...

More information

Overview of the Ruby Language. By Ron Haley

Overview of the Ruby Language. By Ron Haley Overview of the Ruby Language By Ron Haley Outline Ruby About Ruby Installation Basics Ruby Conventions Arrays and Hashes Symbols Control Structures Regular Expressions Class vs. Module Blocks, Procs,

More information

CS 5142 Scripting Languages

CS 5142 Scripting Languages CS 5142 Scripting Languages 10/25/2012 Ruby 1 Outline Ruby Martin Hirzel 2 About Ruby Invented 1995 by Yokihiro Matz Matsumoto Influenced by SmallTalk Everything is an object (even e.g., integers) Blocks

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Installation Download and installation instructions can be found at

Installation Download and installation instructions can be found at IntroductiontoRuby Ruby (http://www.ruby-lang.org/en/ ) is a reflective, dynamic, objectoriented, single-pass interpreted programming language. It also has some functional programming features such as

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE 341, Autumn 2015, Ruby Introduction Summary CSE 341, Autumn 2015, Ruby Introduction Summary Disclaimer: This lecture summary is not necessarily a complete substitute for atting class, reading the associated code, etc. It is designed to be a useful

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC. hapter 1 INTRODUTION SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Objectives You will learn: Java features. Java and its associated components. Features of a Java application and applet. Java data types. Java

More information

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 Course Web Site http://www.nps.navy.mil/cs/facultypages/squire/cs2900 All course related materials will be posted

More information

What is Ruby? CSc 372. Comparative Programming Languages. 27 : Ruby Introduction. Department of Computer Science University of Arizona

What is Ruby? CSc 372. Comparative Programming Languages. 27 : Ruby Introduction. Department of Computer Science University of Arizona What is Ruby? CSc 372 Comparative Programming Languages 27 : Ruby Introduction Department of Computer Science University of Arizona Everything is an object. Everything can be changed: method can be added

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

15.1 Origins and Uses of Ruby

15.1 Origins and Uses of Ruby 15.1 Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in 1996 - Use spread rapidly in Japan - Use is now growing in part because of its use in Rails - A pure object-oriented purely interpreted

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Ruby Primer and Review for Developers

Ruby Primer and Review for Developers A PPENDIX A Ruby Primer and Review for Developers This T appendix is designed to act as both a Ruby primer and review, useful both to developers who want to brush up rapidly on their Ruby knowledge, and

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework Ruby logistics CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP Dan Grossman Autumn 2018 Next two sections use the Ruby language http://www.ruby-lang.org/ Installation / basic usage

More information

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel Introduction: PHP (Hypertext Preprocessor) was invented by Rasmus Lerdorf in 1994. First it was known as Personal Home Page. Later

More information

Semantic Analysis. Lecture 9. February 7, 2018

Semantic Analysis. Lecture 9. February 7, 2018 Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Project 1: Scheme Pretty-Printer

Project 1: Scheme Pretty-Printer Project 1: Scheme Pretty-Printer CSC 4101, Fall 2017 Due: 7 October 2017 For this programming assignment, you will implement a pretty-printer for a subset of Scheme in either C++ or Java. The code should

More information

CPS122 Lecture: From Python to Java

CPS122 Lecture: From Python to Java Objectives: CPS122 Lecture: From Python to Java last revised January 7, 2013 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications JavaScript CS 4640 Programming Languages for Web Applications 1 How HTML, CSS, and JS Fit Together {css} javascript() Content layer The HTML gives the page structure and adds semantics Presentation

More information

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP Dan Grossman Winter 2013 Ruby logistics Next two sections use the Ruby language http://www.ruby-lang.org/ Installation / basic usage

More information

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80)

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80) A Bit of History Some notable examples of early object-oriented languages and systems: Sketchpad (Ivan Sutherland s 1963 PhD dissertation) was the first system to use classes and instances (although Sketchpad

More information

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341 CSE 413 Spring 2011 Introduction to Ruby Credit: Dan Grossman, CSE341 Why? Because: Pure object-oriented language Interesting, not entirely obvious implications Interesting design decisions Type system,

More information

CERTIFICATE IN WEB PROGRAMMING

CERTIFICATE IN WEB PROGRAMMING COURSE DURATION: 6 MONTHS CONTENTS : CERTIFICATE IN WEB PROGRAMMING 1. PROGRAMMING IN C and C++ Language 2. HTML/CSS and JavaScript 3. PHP and MySQL 4. Project on Development of Web Application 1. PROGRAMMING

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22 COSC 2P91 Bringing it all together... Week 4b Brock University Brock University (Week 4b) Bringing it all together... 1 / 22 A note on practicality and program design... Writing a single, monolithic source

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

D Programming Language

D Programming Language Group 14 Muazam Ali Anil Ozdemir D Programming Language Introduction and Why D? It doesn t come with a religion this is written somewhere along the overview of D programming language. If you actually take

More information

C Language Programming

C Language Programming Experiment 2 C Language Programming During the infancy years of microprocessor based systems, programs were developed using assemblers and fused into the EPROMs. There used to be no mechanism to find what

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

What is PHP? [1] Figure 1 [1]

What is PHP? [1] Figure 1 [1] PHP What is PHP? [1] PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server PHP is free to download and use Figure

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

Highlights. - Making threads. - Waiting for threads. - Review (classes, pointers, inheritance)

Highlights. - Making threads. - Waiting for threads. - Review (classes, pointers, inheritance) Parallel processing Highlights - Making threads - Waiting for threads - Review (classes, pointers, inheritance) Review: CPUs Review: CPUs In the 2000s, computing too a major turn: multi-core processors

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Project 5 Due 11:59:59pm Tuesday, April 25, 2017

Project 5 Due 11:59:59pm Tuesday, April 25, 2017 Project 5 Due 11:59:59pm Tuesday, April 25, 2017 Introduction In this project, you will write a compiler for a programming language called Rube, which is a small objectoriented programming language with

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong This is CS50. Harvard University. Fall 2014. Cheng Gong Table of Contents News... 1 Buffer Overflow... 1 Malloc... 6 Linked Lists... 7 Searching... 13 Inserting... 16 Removing... 19 News Good news everyone!

More information

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given MUHAMMAD FAISAL MIT 4 th Semester Al-Barq Campus (VGJW01) Gujranwala faisalgrw123@gmail.com MEGA File Solved MCQ s For Final TERM EXAMS CS508- Modern Programming Languages Question No: 1 ( Marks: 1 ) -

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.

More information

The Java Language Rules And Tools 3

The Java Language Rules And Tools 3 The Java Language Rules And Tools 3 Course Map This module presents the language and syntax rules of the Java programming language. You will learn more about the structure of the Java program, how to insert

More information

A LISP Interpreter in ML

A LISP Interpreter in ML UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,

More information

Ruby : A Dynamic Object Oriented Scripting Language

Ruby : A Dynamic Object Oriented Scripting Language Ruby : A Dynamic Object Oriented Scripting Language Kuldeep Gharat kuldeep@cse.iitb.ac.in November 29, 2004 Kuldeep Gharat kuldeep@cse.iitb.ac.in () Ruby : A Dynamic Object Oriented Scripting Language

More information

Using Scala for building DSL s

Using Scala for building DSL s Using Scala for building DSL s Abhijit Sharma Innovation Lab, BMC Software 1 What is a DSL? Domain Specific Language Appropriate abstraction level for domain - uses precise concepts and semantics of domain

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively

More information

assembler Machine Code Object Files linker Executable File

assembler Machine Code Object Files linker Executable File CSCE A211 Programming Intro What is a Programming Language Assemblers, Compilers, Interpreters A compiler translates programs in high level languages into machine language that can be executed by the computer.

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Lecture - 20 Intermediate code generation Part-4 Run-time environments

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

Introduction CMSC 330: Organization of Programming Languages. Books on Ruby. Applications of Scripting Languages

Introduction CMSC 330: Organization of Programming Languages. Books on Ruby. Applications of Scripting Languages Introduction CMSC 330: Organization of Programming Languages Ruby is an object-oriented, imperative scripting language I wanted a scripting language that was more powerful than Perl, and more object-oriented

More information

Your First Ruby Script

Your First Ruby Script Learn Ruby in 50 pages Your First Ruby Script Step-By-Step Martin Miliauskas @mmiliauskas 1 Your First Ruby Script, Step-By-Step By Martin Miliauskas Published in 2013 by Martin Miliauskas On the web:

More information

Project 5 Due 11:59:59pm Wed, Nov 25, 2015 (no late submissions)

Project 5 Due 11:59:59pm Wed, Nov 25, 2015 (no late submissions) Introduction Project 5 Due 11:59:59pm Wed, Nov 25, 2015 (no late submissions) In this project, you will write a compiler for a programming language called Rube, which is a small objectoriented programming

More information

2. Reasons for implementing clos-unit

2. Reasons for implementing clos-unit A CLOS Implementation of the JUnit Testing Framework Architecture: A Case Study Sandro Pedrazzini Canoo Engineering AG sandro.pedrazzini@canoo.com Abstract There are different reasons why you would like

More information

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley PHP and MySQL for Dynamic Web Sites Intro Ed Crowley Class Preparation If you haven t already, download the sample scripts from: http://www.larryullman.com/books/phpand-mysql-for-dynamic-web-sitesvisual-quickpro-guide-4thedition/#downloads

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

why you should use Ruby

why you should use Ruby LUKE KANIES why you should use Ruby Luke Kanies runs Reductive Labs (http://reductivelabs.com), a startup producing OSS software for centralized, automated server administration. He has been a UNIX sysadmin

More information

At the Forge. What Is Ruby? Getting Started with Ruby. Reuven M. Lerner. Abstract

At the Forge. What Is Ruby? Getting Started with Ruby. Reuven M. Lerner. Abstract 1 of 6 6/18/2006 8:38 PM At the Forge Getting Started with Ruby Reuven M. Lerner Abstract What's behind all the Ruby hype? Reuven walks us through a couple of examples to let the code speak for itself.

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

(Refer Slide Time: 01:40)

(Refer Slide Time: 01:40) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #25 Javascript Part I Today will be talking about a language

More information

Lecture Notes on Programming Languages

Lecture Notes on Programming Languages Lecture Notes on Programming Languages 85 Lecture 09: Support for Object-Oriented Programming This lecture discusses how programming languages support object-oriented programming. Topics to be covered

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 - Spring 2013 1 Memory Attributes! Memory to store data in programming languages has the following lifecycle

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Dynamism and Detection

Dynamism and Detection 1 Dynamism and Detection c h a p t e r ch01 Page 1 Wednesday, June 23, 1999 2:52 PM IN THIS CHAPTER Project I: Generating Platform-Specific Content Project II: Printing Copyright Information and Last-Modified

More information