Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 48

Unit-II Extended Ruby

• Syllabus
• Extending Ruby: Ruby Objects in C, the Jukebox
extension, Memory allocation, Ruby Type System,
Embedding Ruby to Other Languages, Embedding a
Ruby Interpreter

1
Extended Ruby
• Ruby is a object oriented, reflective, general purpose,
dynamic programming language.

• It is an interpreted scripting language which means


most of its implementations execute instructions
directly & freely , without previously compiling a
program into machine language instructions.

2
Extended Ruby
• It is easy to extend Ruby with new features by writing
code in Ruby.

• Once you start adding in low level code written in C,


however, the possibilities are endless.

3
Ruby Objects in C
• Everything in Ruby is an object, and all variables
are references to objects.

• Most Ruby objects are represented as C


pointers to an area in memory that contains the
object’s data and other implementation details.

4
Ruby Objects in C
• This is how Ruby implements object-oriented
code in C:

– a Ruby object is an allocated structure in memory


that contains a table of instance variables and
information about the class.

– The class itself is another object (an allocated


structure in memory) that contains a table of the
methods defined for that class.
5
Ruby Objects in C
• How to represent and access Ruby data-types from
within C.

– Everything in Ruby is an object, and all variables are


references to objects.

– In C, this means that the type of all Ruby variables


is VALUE, which is either a
1. pointer to a Ruby object (VALUE as a pointer) or
2. An immediate value (such as Fixnum)

6
Ruby Objects in C
1. VALUE as a Pointer
– When VALUE is a pointer, it is a pointer to one of
the defined Ruby object structures---you can't
have a VALUE that points to an arbitrary structure.
The structures for each built-in class are defined in
``ruby.h'' and are named RClassname, as
in RString and RArray.

7
Ruby Objects in C
2. VALUE as an Immediate Object
– immediate values are not pointers :  
Fixnum, Symbol, true, false, and nil are stored directly
in VALUE.
– The other immediate values (true, false, and nil) are
represented in C as the constants Qtrue, Qfalse, and Qnil,
respectively.
– You can test VALUE variables against these constants
directly, or use the conversion macros 
8
Ruby Objects in C
• Working with immediate objects
– FIXNUM_P(value) Non zero if value is a fixnum
– SYMBOL_P(value)  non zero if value is a symbol
– NIL_P(value)  Non zero if value is nil
– RTEST (value)  Non Zero if value if neither nil
or false.

9
Writing Ruby in C
• We can write Ruby programs almost directly in C

• That is, you can use the same methods and the same logic, but with
slightly different syntax to accommodate C.

• For instance, here is a small, fairly test class written in Ruby.

class Test   
def initialize     
@arr = Array.new   
end  
 def add(anObject)    
 @arr.push(anObject)   
end
end
10
Writing Ruby in C
The equivalent code in C should look somewhat familiar.
#include “ruby.h” VALUE cTest;
static VALUE t_init(VALUE self) void Init_Test() {
{ cTest = rb_define_class("Test", rb_cObject);
VALUE arr; rb_define_method(cTest, "initialize", t_init, 0);
arr = rb_ary_new(); rb_define_method(cTest, "add", t_add, 1);
rb_iv_set(self, "@arr", arr); }
return self;
}
static VALUE t_add(VALUE self, VALUE anObject)
{
VALUE arr;
arr = rb_iv_get(self, "@arr");
rb_ary_push(arr, anObject);
return arr;
}

11
Working with strings
• In C, we are used to working with a null-terminated strings.
• Ruby strings, however, are more general & may well include
embedded nulls.
• Ruby string objects are actually references to to an RString
structure and the RString structure contains both a length and
a pointer field.
• we can access the structure via the RString macros
INT2NUM(int) Fixnum or Bignum
INT2FIX(int)Fixnum (faster)
CHR2FIX(char) Fixnum
rb_str_new2(char*)string
• C data-types to Ruby objects
RSTRING_LEN(str) Length of the Ruby String
RSTRING_PTR(str) Pointer to String storage
RSTRING_END(str)Pointer to end of string 12
The Jukebox Extension
• Extending Ruby with C is pretty easy.
• For instance, suppose we are building a custom Internet-ready
jukebox for the Sunset Diner and Grill.

• It will play MP3 audio files from a hard disk or audio CDs from a
CD jukebox.

• We want to be able to control the jukebox hardware from a


Ruby program.

• The hardware vendor gave us a C header file and a binary library


to use; our job is to construct a Ruby object that makes the
appropriate C function calls.
13
The Jukebox Extension
• Jukebox example---interfacing C code with Ruby and
sharing data and behavior between the two worlds.
• Jukebox extension framework follows 4 steps

1. API: C Data Type Wrapping

2. Object Creation

3. Allocation Functions

4. Cloning Objects
14
The Jukebox Extension
1. Wrapping C structures
– Wrapping means binds all the vendors jukebox
framework into a single unit to begin the Ruby.

– The vendor’s library that controls the audio CD


jukebox units, and ready to wire it into Ruby.

– The vendor’s header file looks like this

15
The Jukebox Extension
typedef struct _cdjb {
int statusf;
int request;
void *data;
char pending;
int unit_id;
void *stats;
} CDJukebox;
// Allocate a new CDJukebox structure
CDJukebox *new_jukebox(void);
// Assign the Jukebox to a player
void assign_jukebox(CDJukebox *jb, int unit_id);
// Deallocate when done (and take offline)
void free_jukebox(CDJukebox *jb);
// Seek to a disc, track and notify progress
void jukebox_seek(CDJukebox *jb,int disc,int track)
void (*done)(CDJukebox *jb, int percent));
// Report a statistic
double get_avg_seek_time(CDJukebox *jb); 16
The Jukebox Extension

17
The Jukebox Extension

18
The Jukebox Extension
2. Creating Objects
– The basic idea is simple. Let’s say you’re creating
an objects of class CDPlayer in your Ruby
program.
cd=CDPlayer.new

19
The Jukebox Extension
3. Allocation function

20
The Jukebox Extension
4. Cloning Objects

• All Ruby objects can be copied using one of two methods,


dup and clone.

• The two methods are similar: Both produce a new instance of


their receiver’s class by calling the allocation function. Then
they copy across any instance variables from the original.

• Clone then goes a bit further and copies the original’s


singleton class and flags (which means clone is not extensible)

21
Memory Allocation
• To allocate memory in an extension that won't be used
for object storage.

• In order to work correctly with the garbage collector. In


Ruby memory allocation will invoke the garbage collector
to try to allocate the claim space.

• In Ruby, memory allocation is done little bit more work


than the standard malloc.

22
Memory Allocation
Type Description

ALLOC(c-type) Allocates a c-type and casts the result to a pointer


of that type.

Allocates n c-type objects, where c-type is the


ALLOC_N(c-type, n) literal name of the C type, not a variable of that
type.

REALLOC_N(var, c-type, n) Reallocates n c-types
pointer to a c-type.
and assigns the result to var, a

Allocates memory for n objects of c-type on the


ALLOCA_N(c-type, n) stack---this memory will be automatically freed
when the function that invokes ALLOCA_N returns.

23
Ruby Type System
• In Ruby, we rely less on the type (or class) an object and
more on its capabilities. This is known as Duck Typing.

• Hence Duck Typing means an object type is defined by what


it can do, not by what it is.

• Duck typing refers to the tendency of ruby to be less


concerned with the class of an object and more concerned
with what method can be called on it and what operations
can be performed on it.

24
Ruby Type System
• In Ruby, we would use respond_to? or might simply supply pass on
object to a method and to know that an exception will be raised if it is
used improperly.

• If an object is walk like a duck and talk like a duck, ruby interpreter is
happy to treat it as is were a duck.

irb(main): ‘A String’.respond_to?(:to_str)
true
irb(main): 4.respond_to?(:to_str)
false
Irb(main): Exceptioin.new.respond_to?(:to_str)
false
• The above examples are types of Duck typing.

25
Embedding Ruby to other languages
• Ruby vs Ruby on Rails
• Ruby vs C: Seminaries and Differences
• Ruby vs C++: Seminaries and Differences
• Ruby vs Java: Seminaries and Differences
• Ruby vs Perl: Seminaries and Differences
• Ruby vs PHP: Seminaries and Differences
• Ruby can be embedded into Hypertext Markup Language
(HTML).

26
Difference between Ruby and Ruby
on Rails :
• Ruby is a programming language whereas
Ruby on Rails is a Web framework.

• Ruby is an Object Oriented, dynamic,


interpreted scripting language whereas Ruby
on Rails is an Open source Web application
framework, which runs on the Ruby
programming language.

27
Ruby versus C:
• Similarities with C
– As with C, in Ruby,…
• Most of the operators are the same
• Strings go in double-quotes.
• Strings are mutable.
• same sort of command-line debugger available
• Just like man pages, you can read most docs in your
terminal window—though using the ri command.

28
Ruby versus C:
• Differences from C: Unlike C, in Ruby,…
• You don’t need to compile your code. You just run it directly.
• Objects are strongly typed (and variable names themselves have no type at all).
• There’s no macros or preprocessor. No casts. No pointers (nor pointer
arithmetic). No typedefs, sizeof, nor enums.
• There are no header files. You just define your functions (usually referred to as
“methods”) and classes in the main source code files.
• There’s no #define. Just use constants instead.
• All variables live on the heap. Further, you don’t need to free them yourself—
the garbage collector takes care of that.
• Arguments to methods (i.e. functions) are passed by value, where the values
are always object references.
• It’s require 'foo' instead of #include <foo> or #include "foo".
• There’s no semicolons ending lines.
• You go without parentheses for if and while condition expressions.
• Parentheses for method (i.e. function) calls are often optional.

29
Ruby versus C++

• Similarities with C++


• As with C++,in Ruby
• You’ve got mostly the same operators (even ::). << 
• public, private, and protected do similar jobs.
• Inheritance syntax is still only one character, but it’s < instead of :.
• Exceptions work in a similar manner, though the keyword names
have been changed to protect the innocent.

30
Ruby versus C++
• Differences from C++: Unlike C++, in Ruby,…
• There’s no explicit references. That is, in Ruby, every variable is just an
automatically dereferenced name for some object.
• Objects are strongly but dynamically typed..
• The “constructor” is called initialize instead of the class name.
• All methods are always virtual.
• “Class” (static) variable names always begin with @@ (as
in @@total_widgets).
• You don’t directly access member variables—all access to public member
variables (known in Ruby as attributes) is via methods.
• Parentheses for method calls are usually optional.
• You can re-open a class anytime and add more methods.
• There’s only two container types: Array and Hash.
• There’s no type conversions.
• Multithreading is built-in.
31
Ruby versus Java
• Similarities
– As with Java, in Ruby,…
• Memory is managed via a garbage collector.
• Objects are strongly typed.
• There are public, private, and protected methods.
• There are embedded doc tools (Ruby’s is called RDoc).
– The docs generated by rdoc look very similar to those generated
by javadoc.

32
Ruby versus Java
• Differences: Unlike Java, in Ruby,…
• You don’t need to compile your code. You just run it directly.
• There are several different popular third-party GUI toolkits. Ruby users
can try WxRuby, FXRuby, Ruby-GNOME2, Qt, or Ruby Tk for example.
• You use the end keyword after defining things like classes, instead of
having to put braces around blocks of code.
• You have require instead of import.
• All member variables are private. From the outside, you access
everything via methods.
• Parentheses in method calls are usually optional and often omitted.
• Everything is an object, including numbers like 2 and 3.14159.
• There’s no static type checking.
• Variable names are just labels. They don’t have a type associated with
them.
• There are no type declarations. You just assign to new variable names
as-needed and they just “spring up” (i.e. a = [1,2,3] rather than int[] a =
{1,2,3};). 33
Ruby versus Java
• Differences: Unlike Java, in Ruby,…
• There’s no casting. Just call the methods. Your unit tests should tell you
before you even run the code if you’re going to see an exception.
• It’s foo = Foo.new("hi") instead of Foo foo = new Foo("hi").
• The constructor is always named “initialize” instead of the name of the
class.
• You have “mixins” instead of interfaces.
• YAML tends to be favored over XML.
• It’s nil instead of null.

34
Ruby versus Java :
– Ruby based program runs directly as it is an
interpreted scripting language whereas Java-based
codes are first compiled then executed.
– Ruby does not have any data types as Java.
– In Ruby the constructor name is always “initialize”
whereas in case of Java the constructor name is the
name of the class.
– Ruby uses dynamic typing whereas Java uses static
typing.

35
Ruby versus Perl
• Similarities: As with Perl, in Ruby,…
• You’ve got a package management system, somewhat like CPAN
(though it’s called RubyGems).
• Regexes are built right in. Bon appétit!
• There’s a fairly large number of commonly-used built-ins.
• Parentheses are often optional.
• Strings work basically the same.
• There’s a general delimited string and regex quoting syntax
similar to Perl’s. It looks like %q{this} (single-quoted),
or %Q{this} (double-quoted), and %w{this for a single-quoted list
of words}. You %Q|can| %Q(use) %Q^other^ delimiters if you
like.
• You’ve got double-quotish variable interpolation, though
it "looks #{like} this" (and you can put any Ruby code you like
inside that #{}).
• You’ve got embedded doc tools (Ruby’s is called rdoc). 36
Ruby versus Perl
• Differences : Unlike Perl, in Ruby,…
• You don’t have the context-dependent rules like with Perl.
• A variable isn’t the same as the object to which it refers.
Instead, it’s always just a reference to an object.
• Although $ and @ are used as the first character in variable
names sometimes, rather than indicating type, they
indicate scope ($ for globals, @ for object instance,
and @@ for class attributes).
• Array literals go in brackets instead of parentheses.
• Composing lists of other lists does not flatten them into
one big list. Instead you get an array of arrays.
• It’s def instead of sub.
• There’s no semicolons needed at the end of each line.

37
Ruby versus Perl
• Differences : Unlike Perl, in Ruby,…
• Objects are strongly typed. You’ll be manually
calling foo.to_i, foo.to_s, etc., if you need to convert
between types.
• There’s no eq, ne, lt, gt, ge, nor le.
• There’s no diamond operator (<>). You usually
use IO.some_method instead.
• The fat comma => is only used for hash literals.
• There’s no undef. In Ruby you have nil. nil is an object (like
anything else in Ruby). It’s not the same as an undefined
variable. It evaluates to false if you treat it like a boolean.
• When tested for truth, only false and nil evaluate to a false
value. Everything else is true (including 0, 0.0, and "0").

38
Ruby versus Perl :
– Perl is unorganized, messy because of its free nature
whereas Ruby is a well-organized language.
– Perl has multiple variable types whereas Ruby has
only one variable type reference to an object.
– Perl is less object-oriented whereas Ruby is more
object-oriented programming language.
– Perl supports more Unicode properties than Ruby.

39
Ruby versus PHP
• Similarities: As in PHP, in Ruby…
• Ruby is dynamically typed, like in PHP, so you don’t need to
worry about having to declare variables.
• There are classes, and you can control access to them like in PHP
5 (public, protected and private).
• Some variables start with $, like in PHP (but not all).
• There’s eval, too.
• You can use string interpolation. Instead of doing "$foo is a
$bar", you can do "#{foo} is a #{bar}"—like in PHP, this doesn’t
apply for single-quoted strings.
• Ruby has exceptions, like PHP 5.
• There’s a fairly large standard library.
• Arrays and hashes work like expected, if you
exchange array() for { and }: array('a' => 'b') becomes {'a' => 'b'}.
• true and false behave like in PHP, but null is called nil. 40
Ruby versus PHP
• Differences: Unlike in PHP, in Ruby…
• There’s strong typing. You’ll need to call to_s, to_i etc. to convert
between strings, integers and so on, instead of relying on the language
to do it.
• Strings, numbers, arrays, hashes, etc. are objects. Instead of calling
abs(-1) it’s -1.abs.
• Parentheses are optional in method calls, except to clarify which
parameters go to which method calls.
• The standard library and extensions are organized in modules and
classes.
• Reflection is an inherent capability of objects, you don’t need to
use Reflection classes like in PHP 5.
• Variables are references.
• There’s no abstract classes or interfaces.
• Hashes and arrays are not interchangeable.
• Only false and nil are false: 0, array() and "" are all true in conditionals.
41
• Almost everything is a method call, even raise (throw in PHP).
Ruby versus PHP :
– Web development and deployment is very simple
with PHP as compared to Ruby.
– Using Ruby, Ruby on Rails was created for the
designing of Web applications whereas PHP is
designed for back-end Web development.
– Facebook is PHP based application whereas Twitter
is Ruby-based application.
– PHP has a better performance on the basis of
execution as compared to Ruby. PHP executes faster
than Ruby as PHP has fewer lines of code as
compared to Ruby

42
Ruby versus Python
• Similarities: As with Python, in Ruby,…
• There’s an interactive prompt (called irb).
• You can read docs on the command line (with
the ri command instead of pydoc).
• There are no special line terminators (except the usual
newline).
• String literals can span multiple lines like Python’s triple-
quoted strings.
• Brackets are for lists, and braces are for dicts (which, in Ruby,
are called “hashes”).
• Arrays work the same
• Objects are strongly and dynamically typed.
• Everything is an object, and variables are just references to
objects.
• You’ve got embedded doc tools (Ruby’s is called rdoc). 43
Ruby versus Python
• Differences: Unlike Python, in Ruby,…
• Strings are mutable.
• You can make constants (variables whose value you don’t
intend to change).
• There are some enforced case-conventions (ex. class names
start with a capital letter, variables start with a lowercase
letter).
• There’s only one kind of list container (an Array), and it’s
mutable.
• Double-quoted strings allow escape sequences (like \t)
• You never directly access attributes. With Ruby, it’s all
method calls.
• Parentheses for method calls are usually optional.
• There’s public, private, and protected to enforce access,
instead of Python’s _voluntary_ underscore __convention__. 44
Ruby versus Python
• Differences: Unlike Python, in Ruby,…
• “mixins” are used instead of multiple inheritance.
• You can add or modify the methods of built-in classes. Both
languages let you open up and modify classes at any point,
but Python prevents modification of built-ins — Ruby does
not.
• You’ve got true and false instead
of True and False (and nil instead of None).
• When tested for truth, only false and nil evaluate to a false
value. Everything else is true (including 0, 0.0, "", and []).
• It’s elsif instead of elif.
• It’s require instead of import
• Python supports just one kind of anonymous functions,
lambdas, while Ruby contains blocks, Procs, and lambdas.
45
Ruby versus Python :
– Ruby can be very hard to debug at times while
Python is very explicit and easy to read.
– Usage of blocks are present in Ruby whereas usage
of modules and better namespace handling are
present in Python.
– Ruby based apps are Twitter, Github, Hulu etc.
whereas Python-based apps are Youtube, Instagram,
Bit torrent, etc.
– Ruby has a Web framework called Ruby on Rails
whereas Python has a web framework called
Django.

46
Embedding a Ruby Interpreter
• In addition to extending Ruby by adding C code, you can also turn the
problem around and embed Ruby itself within your application.
• Here's an example.
#include "ruby.h"
main() {   /* ... our own application stuff ... */   r
uby_init();   ruby_script("embedded");   
rb_load_file("start.rb");   
while (1) {    
 if (need_to_do_ruby) 
{      
 ruby_run();     
}     /* ... run our app stuff */  
 } }

47
Embedding a Ruby Interpreter

48

You might also like