Understanding { } and block_given

  • Thread starter Srijayanth Sridhar
  • Start date
S

Srijayanth Sridhar

[Note: parts of this message were removed to make it a legal post.]

Hello,

I have the following:

class DSL
def DSL.load filename
dsl = new
dsl.instance_eval(File.read(filename))
dsl
end
def to sym,*args,&block
if block_given?
b=class << self;self;end
b.instance_eval {
define_method(sym,*args,&block)
}
end
end
def method_missing sym,*args
"#{sym}"
end
alias :say puts
end

foo=DSL.load("sample.dsl")


sample.dsl:

to smile do
say ":)"
end
to be_polite {
say "thank you"
}
smile
be_polite


The resulting output is:

moonwolf@trantor:~/ruby/dsl/todo$ ./dsl.rb
:)
moonwolf@trantor:~/ruby/dsl/todo$

be_polite and indeed, anything enclosded in {} doesn't seem to be eval-ed as
blocks. Why is this?

Jayanth
 
S

Srijayanth Sridhar

[Note: parts of this message were removed to make it a legal post.]

This is definitely not a block_given thing.

block is coming through as a NilClass it seems.

puts block.class yields NilClass. The strange bit is that when I do it
outside of instance_eval with just a define_method under irb, it works as
expected. I am lost.

Anyone?

Jayanth
 
F

F. Senault

Le 08 mai à 11:42, Srijayanth Sridhar a écrit :
[Note: parts of this message were removed to make it a legal post.]

This is definitely not a block_given thing.

It's an operator precedence thing. {} binds at a higher precedence than
do/end, meaning that, in the absence of parentheses, in one case, it's
the first function that takes the block and in the other, it's the
second one.

For instance :
no block
=> nilblock

In the first case, it's puts who gets the block (and discards it). In
the second case, it's my function. Compare to :
no block
=> nilno block
=> nilblock
=> nilblock

Fred
 

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

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,156
Latest member
KetoBurnSupplement
Top