Threads and Synchronization in Ruby..!

Ruby No Comments »

I was just free this weekend,so just gotta a chance and dropped myself with a little program on threads and synchronization in ruby.This program  generates a secret number which is implemented as sync_server_thread on the server side and then assigns the same variable on the the client side.

In this program , I took care of things like mutual exclusion and deadlocks.In the very first line I am requiring thread class and creating a new object for Mutex(a class which handles stuff related to mutual exclusion of threads), a instance of condition variable (a condition variable is a semaphore which is mainly used in accordance with mutex class,its main purpose is to take of processes in the critical section which are stuck in themselves while waiting for some external resources like non ruby programs).The sync_var_1 and sync_var_2 are local variables which will contain the secret number that will be generated at the server side and will be assigned to the client side program.

The first thread is the server side which runs on the server side and is responsible for generating the secret number on the server side. In The server side thread we can see that the condition variable sync_prevention.wait, there is no such implication on the presence of this statement in the program,but I have actually kept it if in case we include any functionality in the program which generally calls some external program to run as a part of the thread for example if I use a third party secret number generator for generating a secure secret number which may take a ample of time to generate the secret number.The wait method of condition variable generally tends to release the current thread under mutex and  re invokes that process later when the external program has responded.

Similarly in the second thread, the signal method of the condition variable tends to wake up the first thread waiting for the external resource.By doing this, we can maintain a balance of load on the server where multiple requests for generating the secret number.

The join method is one of the coolest and a must use method in the Thread class,I call it a must use method because when a ruby program containing some code related to thread runs,All the threads creating during the course of execution of the program will and must be killed once the program exits out of its execution.So To make sure that these threads complete at their whole, we use the associate them the join method.And finally the sync_diff is make sure that the same values at the server as well as the client remain intact at any point of time and the difference between them should always be zero.

 There are some implcations in the existing program, that the client and server run on the same file. In my coming posts you will see that the

the server thread runs under the server enviornment like webbrick or mongrel or may be a backgroundDRB…!…and the client thread will be running as a controller process in case of our rails app and will be synchronized with the server’s secret value.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

String in Ruby-Tutorials…!

Ruby 1 Comment »

Strings In Ruby

String is nothing but an object that holds a arbitrary sequence of bytes which typically represents characters.

The string .new is used to create new objects of strings.

The Secret of the Exclamation Mark(!)

Ex: Delete and Delete!

-The Method with ! mark tend to modify the behaviour of the receiver.

-Those method without a ! mark tend to return a new string as an output.

Mixins For Ruby

Comparables:

<, <=, ==, >=, >, between?

Enumarable: collect, detect, each_with_index, entries, find, find_all, grep, include?, map, max, member?, min, reject, select, sort, to_a

String Multiplication

Strings in ruby do understand Multiplication.

But don’t compare this with addition and division because they might throw errors

In case of the %( Division sign) the string evaluates “Hello Ruby” as a format specification. Since its not able to find any format specification of its kind in Kernel: sprintf class method, it tends to ignore the % 3 argument as directly displays the “Hello Ruby”.

Element Reference And Element Assignment In Strings

This comes into play when you want to insert or substitute a string with some kind of special characters, values or other string.

The element referencing is based on the offset and the length.

The range and length combination can also be used for element referencing

Secure your strings using crypt

The string class provides the crypt method for crypting a string and mainly used for secure data transmission.

Its takes an argument as a salt string which should be minimum 2 characters long

Dump of a String

The dump method produces the version of the string with all non printing characters replaced by \ notation and all special characters escaped.

Splitting your strings using each

each” splits your string based on the input parameter and then supplies the substring to the evaluating block.

Syntax:

string”.each (parameter){|substring| play with substring}

 

When we pass the no parameters in the first case, we can see that the string has been passed as it is.

In the second case the string is substring is created wherever it finds the letter “e”

In the last scenario the string is evaluated wherever its finds the newline character.

Scanning of a String

The scan function tends to parse the string based on a matching pattern (which is RegEx) .

The result generated is either added to an array or may be passed to the evaluating block.

 

Splitting the String

The scan divides the string into two sub strings and passes these substrings as a result to an array.

The difference between split and scan is split takes an input parameter called “limit”.The limit is generally a positive number which divides the string into the substrings based on the limit.

 

In the first case, when no parameters are passed to the split method, it tends split the string wherever it finds the whitespace.

In the second case,we are splitting the string at every character that it comes across.

In the third scenario,we pass the limit of 3 as the second parameter so, it will parse and break the string into exact 3 division of its own as shown in the example.

Squeezing the strings

The squeeze method tends to build a new string string by elimination of same set of characters that occur in the string and replacing them with a single character of its same kind.

 

Swapcasing your Strings

The swapcase tends to convert the string characters with upcase to downcase and vice versa.

 

String Interpolation

The word interpolation sounds pretty scary, but interpolation is nothing but the ability to insert some kind of value, like a variable or some kind of code snippet into the string.

Double quoted strings allow using #{…} notation for insertion of evaluated values within the string.

In the second case you can escape the brackets for instance, class and Global variables.

But in case of local variables you cannot skip those braces as you can see the output has failed to resolve the local variable name.

The Q Factor in strings

Ruby allows you to create string using %q and %Q followed by delimiter of your choice.

These are mainly used when your string has many single quotes as well as double quotes which will definitely bug you if you try to escape them using the \ .

Here %q is equivalent to single quote and %Q is equivalent to the double quote

Difference between sub and gsub

The main difference between these two instance methods comes in focus when regular expressions are mingled with your strings.

As we can in the example, sub tends to substitute only for the first match where as gsub will substitute for all the matches found within the string.

Difference between capitalize and upcase

Capitalize returns a string with the first character converted to uppercase and the remaining to the lowercase where as the upcase converts all the characters in the strings to the upper case.

Difference between chomp and chop

chomp” returns a new string with a given record separator removed from end of the string if present.

chop” returns a new string with the last character removed.


Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

Ruby’s Believe It Or Not

Ruby 1 Comment »

Hi Folks, Just mentioning some cool facts and truths about my friendly programming language that is Ruby…

These are like brain teasers which any one can ask you at any point of time.

  • -Variables in ruby are not the object instead they are mere refrence to the objects that are being created.
  • Methods from the kernel are mixed into the object class,the object class is universaly available and so are the methods from the kernel class.
  •  Difference between Include and extends?
    -Include appends the features of a namespace to the current namespace, where as extend appends the functions of a module to and object.
    -With Include, the module’s methods become available to the instance methods,and with extend they become available as a class methods.
  • Difference between load and require of a file?
    - The load tends to read the file and inserts the file at that particular point in the source file so that its definitions become available at tat particular point,where as a require is same as load but it does not the load the file if has already been loaded.
  • Classes in ruby don have what we call a “name”, instead they are constants referring to the object of type Class  since in ruby Class is a class
  • self is a pseudovariable which can be used on the instance methods of the class, it generally refrences to the current receiver that is the object on whcih the
    instance method is invoked.
  • Alias provides a means by which we can have synonyms for methods.
    ex: alias newname oldname
    and here the number of parameters must be the same as the old one.Theres something called as alias_method which behaves similarly to the alias method
    expect the fact that the parameters must be comma separated values.
  • Singleton methods are methods that are defined on per object basis, that is theey have sole impact on the object rather then the class or the superclass.
  • Reflection in ruby defines an active enviornment which queries the object that deines themselves,extends themselves or may change dynamically.
  • In Ruby,Control structures are not objects.
  • This is something cool which I am going to tell you now,for a given object, you can find out a list of methods available on that object by using the “method” method.
    For ex:”test”.method will print all the methods avalible for the string class
    and this “method” method is defined in the oject class.
  • The class Module has a method ancestors that returns a list of modules included in the given module
  • The ObjectSpace module has access to all live modules.The method  “idtoref” converts the object id to an object reference
    and there is also another cool method called each_object that iterates over all live objects.
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

Fixing the precision for floating points numbers in Ruby

Ruby No Comments »

I really came across this beautiful function which allows you to set the precison for a floating point numbers.

The situation was somewhat like this, I wanted the floating point numbers like 1.5 to be displayed as 1.50 i.e upto 2 decimal places fixed after the point.

So , my dear Ruby provides a beautiful function termed as number_with_precision which allows you set the number of digits after the decimal point.

The following is the way of how u can use it:Here I am setting the floating point numbers upto 2 decimal places

<%= number_with_precision(floating_point_number,2) %>

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

WordPress Theme & Icons by N.Design Studio. Packaged by Edublogs - education blogs.
Entries RSS Comments RSS Login