ruby on rails - block_given? always returns false -


so trying write method_missing in ruby, method_missing has 3 parameter shown

def method_missing(mid,*args,&block)      if (args.empty? && !block_given?)           puts " sample 1  no arguments given nor block"       elsif (!args.entries.empty?)           puts " there arguments given"       elsif (block_given?)            puts "there ?code given"     end  end  

the problem calling instance.anything { " block" } returns " sample 1 no arguments given nor block". it's clear block_given returns false , why?

you have bit overcomplicated logic in method , that's main reason why doesn't work according expectations. there no issue block_given?

also, don't see reason in args.entries.empty? usage. args.empty? gives same result, looks more clear.

original method rewritten this, notice didn't cover case when method can called arguments , block. don't know if intent or not.

def method_missing(mid, *args, &block)   if args.count > 0     puts "there arguments found"   else     if block_given?       puts "there code found"     else       puts "sample 1  no arguments given nor block"     end   end end    

example shows block_given? works properly:

class   def method_missing(mid, *args, &block)     p block     p block_given?   end end  a.new.aaaa nil false  => false   a.new.aaaa { "aaaa" } #<proc:0x007fabd313d090@(irb):8> true  => true   

Comments