How to use a method inside a block

Hi everyone ,

Was wondering, how am I supposed to use a method inside a block , as for
example , how am I supposed to use mult function in the flowing block :

(1…5).each do |n|
mult(n,2)
end

def mult(x,y)
x*y
end

I keep getting undefined method ‘mult’ for main:Object , while self for
both inside the block and outside it is main

Thanks in advance .

On Mon, Oct 17, 2011 at 6:10 PM, Eqbal Q. [email protected] wrote:

x*y
end

I keep getting undefined method mult for main:Object , while self for
both inside the block and outside it is main

mult needs to be defined before it’s used.

Hey,

Try putting the method definition before the block:

def mult(x,y)
x*y
end

(1…5).each do |n|
mult(n,2)
end

This should work, I’m pretty sure. It has to do with the way Ruby treats
methods/variables that are first defined/invoked in a block. Since
blocks open up a new scope (even if it’s just a nested scope
encompassing the previous), anything the parser sees that’s first
referenced in a block and isn’t defined will throw an error.

That’s my understanding, anyway.

-Luke

On Mon, Oct 17, 2011 at 4:10 PM, Eqbal Q. [email protected] wrote:

(1…5).each do |n|
mult(n,2)
end

def mult(x,y)
x*y
end

I keep getting undefined method mult for main:Object

You’re calling your method before you’ve defined it.

You help is highly appreciated .
You are absolutely right . it’s working perfectly now .

Cheers
Eki

Your help is highly appreciated .
You are absolutely right . it’s working perfectly now .

Cheers
Eki

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs