Circular Arrays in Ruby

Ruby On Rails No Comments »

Circular Array In ruby

The main logic behind this post says that “How do we move through the array indices in a circular manner” i.e whenever we reach the last index the control should be transferred back to the first index and vice versa. I actally means to say the array should navigate like a circular linked list.

So,The example below will clarify its usage and the logic behind it.

In my case,  I had a query getting some values for me in an array.The task was to paginate the array based on each values or index of the array one at a time.i had tried wot the standard paginator bulit into ruby but it provided me with a little freaky control over the array for circular pagination.So i decide to write some own logic of mine for a for this particular pagination.

The below code tells us the story for having a circular pagination.

The line 1 is nothing but the method get person details which takes the parameter as the current user id which is displayed on the page.

The line 2 is the query whcih gets the data for me for the pagination purpose.

 In the line 3  I am initalizing a new array

The do loops extracts all the Ids present in the array and pushes those ids into the array @o_ids.

 Now, what the return does is, it takes the its takes in the parameter id  of the current user being displayed and first finds the index of that particular id in the array and then decrements the index by 1 to get the value previous to that index and finally resolves the values at the index using the at instance method of the Array class. The second values returned is nothing but the postion of the actual id coming as a parameter, and the third return values is the value next to the current id.In the third case I check that the incremented Id does not exceed the length which will inturn throw a nil error while pagination.So using the ternary operator it evaluate the id back to zero index whenver it exceeds the last index of the array making the array circular

For Example:

Imagine that the array @o_ids has the following values and the id of the current user that is been shown is 103 so the get_person_details get 103 as the parameter. The line 21 shows the output which is 102(id decremented from the current Id), the 103(current Id) and 104(the incremented Id)

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 -2

Rails Articles No Comments »
  • Here Documents in strings
    Here documents are nothing but strings that are inherently multiline.
  • str=<<EOF
    Raghu is giving a presenation,
    he know ruby very well.
    EOF
  • Here documents can also be stacked into a method like
    def foobar(<<str1,<<str2,<<str3)
     This is a cool thing
     And this is great.
     str1
     This is the second cool thing
     and it is also great
     str2
     This is third cool thing
     and now its becoming hot
     str3
    end
  • String Compression:
    The zlib library provides means for compressing and decompressing strings and files mailt faster db access,to optimize the network or may be obscure
    the strings  so that they are not possibly readable
    The Deflate and Inflate classes have the methods defalte and inflate for ths purpose.The deflate takes parameter whch defines the quality of compression and speed
    BEST COMPRESSION-results in a smallest compressed string
    BEST SPEED- Compresse faster buts does not compress as much
    DEFAULT COMPRESSION-Provides a tradeoff between
  • -How does method invocation takes place in ruby on rails?
    For example: myobject.method
    -Ruby first searches for singleton methods of myobject
    -Then it defines the myobject class
    -Then the methods defined in the myobjects ancestors
    In case if the mymethod is not found,ruby seraches the default method called method_missing
  • - Methods without parenthesis are valid in ruby.
     For example: foobar a,b,c
  • -There are no boolean types in Ruby.Instead there is the TRuecalss and the Falseclass with its instance as true an false
  • -loop is not a keyword instead its a method defined into the kernel module
  • -what is the differenece .. and… in ranges?
    ..is inclusive of the upper bound and the … is not exclusove of the upper bound.ex5..10 will consider 10 but …will not consider 10
  • what kind of a scope does the intialize method of a class have?
    -The intialize method is always private
  • The methods ending with an ! mark are said to be destructive methods.These are said to destructive since these methods tend to modify the behaviour of the receiver i.e the receiver will not hold the values before it was applied to this method.
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

Back from the Barcamp4 Pune

Barcampz...! No Comments »

Back from the BarCamp Pune

Here are the collection of snaps from the friends cam…which seem to be pretty cool….!

Check out the geek campers below ……..:)

Ajax :Redefining presentation going below

Why Ruby? Presentation by Sidu Ponappa

Me and my group ahving a chat with sidu about “WAZZUP IN RUBY”…!

Finally…presenting the geek returning home after barcamp

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