Keywords, &blocks and instance_eval

J

Jim Freeze

Hi

I am fine tuning a DSL and came across the situation
where I needed a method with the name of 'module'.

In my previous revision of the DSL, I did the following:

------------
class C
def initialize
yield self
end
def module
puts "in C#module"
end
end
-------------

The user code would then look like:

C.new do |c|
c.module
end

But, I didn't really like requiring (or explaining)
why the 'c.' was required. So I rewrote the class to be:

------------
class C
def initialize(&block)
instance_eval &block
end
def module
puts "in C#module"
end
end
-------------

But, when a method name is called that is dear to Ruby heart,
like 'module', an error is generated:

C.new do
module
end #=> syntax error

Is there any way to have get the effect of the above

c.module

with the instance_eval?

Thanks
 
R

Robert Klemme

Jim said:
Hi

I am fine tuning a DSL and came across the situation
where I needed a method with the name of 'module'.

In my previous revision of the DSL, I did the following:

------------
class C
def initialize
yield self
end
def module
puts "in C#module"
end
end
-------------

The user code would then look like:

C.new do |c|
c.module
end

But, I didn't really like requiring (or explaining)
why the 'c.' was required. So I rewrote the class to be:

------------
class C
def initialize(&block)
instance_eval &block
end
def module
puts "in C#module"
end
end
-------------

But, when a method name is called that is dear to Ruby heart,
like 'module', an error is generated:

C.new do
module
end #=> syntax error

Is there any way to have get the effect of the above

c.module

with the instance_eval?

No. Unless you resort to using string instead of a block and do some
gsub'bing on the string which inserts the "c." part (or "self." in that
case).

"module" and "class" are keywords. That's why you never can do
"class.new..." but always have to "self.class.new...".

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top