The Passionate Craftsman

Ruby, PHP, MySql, Software engineering and more.

Thursday, 29 December 2011

How to call a private method in Ruby

If you want to call a private method in Ruby - for any reason - you can use send, method and instance_eval:



class Foo

private
def bar
puts 'You called bar'
end
end

> foo = Foo.new
foo.bar # this, of course, throws an error
NoMethodError: private method `bar' called for #
from (irb):129
from :0

> foo.send(:bar)
You called bar
=> nil
m = foo.method(:bar)
=> #
> m.call
You called bar
=> nil
> foo.instance_eval { bar }
You called bar
=> nil


Remember you cannot use eval to call a private method:


> eval('foo.bar')
NoMethodError: private method `bar' called for #
from (irb):140
from (irb):140
from :0



Labels: ,

Saturday, 27 June 2009

Metaprogramming in Ruby

Dave Thomas is on infoq. He explain how metaprogramming in Ruby works. He explains many hidden and unknown features of the Ruby language, for instance the definition of a class can be changed in real time and is possible to define a method using a conditional statement. I have appreciated the the comments about Java, a programming language that was designed for mediocre programmer to commit less mistakes. In Ruby you have less restrictions and the talent is preferred instead of the fear that you have poor quality programmers in your team.

Reference:
http://www.infoq.com/presentations/metaprogramming-ruby

Labels: