Friday, September 24, 2010

ruby send method

Hi all

I am started using the method named "send".

We can use this to call the method using object.

class User

def say_hello
"Hello"
end

end

u = User.new
puts u.send(:say_hello)

Here the class "User" is having the method called say_hello. We can create an object for the user class and call the method using the method "send"

Cheers,
vadivelan

Tuesday, September 21, 2010

ruby extend method

Hi all,

I have seen the method named "extend" used in a line of code in Plugin. Then i started searching for the use of method "extend". And i found the following

consider the example

module Friend
def say_hello
"hello am inside module"
end
end

class Person
def say_hello
"hello am inside class"
end
end

p = Person.new
puts p.say_hello #=> hello am inside class

p.extend(Friend) #=> include all the instance method from Module "Friend"
puts p.say_hello #=> hello am inside module


So the extend method is used to include the Module.
Without this we cannot call the method inside the module using the Person object. Even if i added include the module in the class, it wont calls the module method. The instance method inside the class gets called for the object(Person class).

Wednesday, September 15, 2010

Use of Proc & proc

Hi

I have used "proc" to run/block validation in model. But now i learned something more about proc.
In ruby, "Proc"(procedure) refers to the block of code, we can reuse it. Block of code assigned to the object.

"Proc" => Starts with capital letter refers to (class name)
"proc" => Refers to the proc object

We can use both the keywords to create a proc by defining any block to them.

below sample code to create a proc and call that proc to execute the block of code

accepts_any_arg = Proc.new{ |a,b,c|
puts "#{a} #{b} #{c}"
}
accepts_any_arg.call(1)
result: 1
accepts_any_arg.call(1,2)
result: 1 2
It just neglects the number of arguments required or passing to that proc, it is working without any argument error. It assigns nil value to arguments which are not passed.


throws_args_error = proc{ |a,b,c|
puts "#{a} #{b} #{c}"
}
throws_args_error.call(1,2,3)
result: 1 2 3
throws_args_error.call(1)
result: Throws "ArgumentError"
it is checking the number of arguments


Thanks,
Vadivelan