[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Passing methods as parameters - the nice way?

Stefan Rusterholz

10/24/2007 4:24:00 PM

Søren Andersen wrote:
> Hello all,
>
> I told it to:
> def call_action
> if(@action_method)
> send(@action_method)
> end
> end
>
> which works fine, as long as my method is defined "in the wild":
>
> def foo
> puts "foo called"
> end
>
> interface.set_action(:foo)
> interface.call_action => foo called

I'd suggest using blocks instead of the above construct. Your code
transformed:

def on_action(&block)
@action = block
end

def action
@action.call if @action
end

obj = Object.new
def obj.foo; puts "foo on #{self.inspect} called"; end

interface.on_action { obj.foo }
interface.action

# alternatively:
interface.on_action(&obj.method(:foo))
interface.action

Blocks are far more flexible than passing a method name or instance.

Regards
Stefan
--
Posted via http://www.ruby-....