ruby notes(4)

  • Ruby calls serialization marshaling. Saving an object and some or all of its components is done using the method Marshal.dump. Later on you can reconstitute the object using Marshal.load
  • In Ruby, regular expressions are objects (of type Regexp) and can be manipulated as such. // is a regular expression and an instance of the Regexpclass, as shown below:
    //.class    # Regexp
  • In Ruby, classes are never closed: you can always add methods to an existing class.
  • In Ruby, a class can only inherit from a single other class.
  • Use require_relative (only works for Ruby 1.9) when the location of the file we’re loading is relative to the file we’re loading it from –  both in the same directory
  • if an object fails to find any such method, it raises a NoMethodError exception – unless you have provided the object with a method called method_missing
  • Blocks are not objects, but they can be converted into objects of class Proc.
    1. use procs as parameter (method cannot be used as parameters)
    def some_mtd some_proc
    puts ‘Start of mtd’
    puts ‘End of mtd’
    endsay = lambda do
    puts ‘Hello’
    endsome_mtd say

    The output is:

    Start of mtd
    End of mtd
    1. Here’s another example of passing arguments using lambda.
    a_Block = lambda { |x| “Hello #{x}!” }
    puts ‘World’ => Hello World!
  • symbols are more efficient than strings. Two strings with the same contents are two different objects (different object_id), but for any given name there is only one Symbol object. This can save both time and memory.
  •  h = {:nickname => ‘IndianGuru’, :language => ‘Marathi’, :lastname => ‘Talim’}
    puts h

    The output is:

    {:nickname=>”IndianGuru”, :language=>”Marathi”, :lastname=>”Talim”}

    Another way (using name: value pairs to create a hash if the keys are symbols) of doing the same thing is

    h = {nickname: ‘IndianGuru’, language: ‘Marathi’, lastname: ‘Talim’}
    puts h

    The output is:

    {:nickname=>”IndianGuru”, :language=>”Marathi”, :lastname=>”Talim”}

    An exception to the shorter {symbol: value} syntax is when you would like to use a numeric key:

    hash = {1: ‘one’} # will not work
    hash = {1 => ‘one’} # will work

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s