How to create procedure and passing argument as code block ??

In Ruby a Proc is an object that holds a chunk of code. We can create Proc by ” lambda( )” method. To call the code block we have to use call method of Proc.

And if we want this Proc object to pass as code block argument then we have to append an ‘&’ with Proc name.

One thing to remember that we have to associate an ‘&’  with the parametername to pick up any code block in the method definition. The whole thing is as follows —-

class Report

def output_report (&Outputblock)
Outputblock.call(  )
end

end

# code-block here with Proc

hello = lambda do

puts('Hello')
puts('I am inside a proc')
end

report = Report .new

report.output_report( &hello)

————————————————————-

 

In the above code “hello” is the created procedure.

Advertisements

How to Create Interface ??

In ruby basically we have no built in option for creating Interface. We just need to force the base class method to act like an Interface method.

Example :–>

class InterfaceName

def show

raise ‘Exception! This method must be implemented before accessing it.’

end

end

—————————

class SubclassName < InterfaceName

….

end

————————

If we want to do the following then it raises Exception…

SubclassName . show

Marshaling of Object

Marshalling is an interesting thing. Marshaling is the process by which object can be converted into byte streams  and stored outside the application. So, we can use/read this saved object from another application and copy of the originally saved object can be reconstituted.

Rails uses marshalling for storing session data.

Basics of Ruby

Ruby is an object oriented programming Language. It is dynamic in nature. Basically it has no primitive data types. It has no built in supports of Interface as dose Java.

Variable Declaration :

  • local variable–> varname.
  • instance variable–> @varname.
  • global variable–> $varname.
  • class variable–> @@varname.

Class method Definition :

def ClassName. methodName
end

def  self. methodName
end

class << self
def methodName

end
end

Inheritance :

class SubclassName < SuperclassName
end

Ruby code block :

objectName . Method do

|object|  puts(object.value)

end

Name Spaces:

The double colone(::) is Ruby’s namespace resolution operator. The thing to the left must be a class or module and the thing to the right is a constant which is defined in that class or module.

Example :–> Math :: pi.

Attribute accessor methods :

  • Attribute setting method

attr_writer :duration

  • Attribute getting method

attr_reader :name, :artist

Read the rest of this entry »