ruby - Why does passing a method as an argument (&block) not work? -
clock
takes block:
def clock(&block) hours = time.new.hour puts hours hours.times block.call end end
this works, , puts "dong"
on screen, based on hours of today:
clock puts "dong..." end
i'm trying pass dong
method:
def dong puts "dong..." end
to clock
block. this:
clock(dong)
throws error:
`clock': wrong number of arguments (1 0) (argumenterror)
can explain why first 1 works, second doesn't? have explicitly define code block you're passing, or can reference method code block?
because
clock(dong)
doesn't call clock
dong
method block, calls result of calling dong
method. thus, argument error, because try call method (clock
) 1 argument, while expected none (except optional block, not count).
to use dong
method block in invocation, can do:
clock(&method(:dong))
method(:dong)
give method
object representing dong
method (instead of calling it), while &
convert proc (and block).
Comments
Post a Comment