December 18, 2012

Meta-programming in Ruby : Part 2 : Method Missing


Code 1


class Hash
def method_missing(m,*a)
if m.to_s =~ /=$/
self[$`] = a[0]
elsif a.empty?
self[m]
else
raise NoMethodError, "#{m}"
end
end
end

x = {'abc' => 123}
p x['abc']
print "\n"

x.foo = :baz
x.goo = "duh"
x.x&z = 10
p x


Result 1


[root@localhost ruby_tutor]# ruby method_missing1.rb
123

{"abc"=>123, "foo"=>:baz, "goo"=>"duh"}


Code 2


class Hunt
@@arr = []
def show;
@@arr;
end

def method_missing(name, *args)
begin
@@arr.send(name, *args)
rescue
"'#{name}' method has NOT been implemented YET"
end
end
end

he = Hunt.new

he << 123
he << "Be happy, Son!"
p he.show
puts he.flyswim


Result 2


[123, "Be happy, Son!"]
'flyswim' method has NOT been implemented YET



Code 3
Remember that method_missing will provide a block if one is given


def method_missing(name, *args, &block)
block.call(*args) if block_given?
end

no_method("Ask","why", "study this !"){ |*args| p args }



Result 3


[root@localhost ruby_tutor]# ruby method_missing_bloc_CROSS-REF.rb
["Always demand", "why you have to", "study this or that or whatever!"]


No comments:

Post a Comment

A Tip for Job Search: Gold Rush Skills

  If you need to make some money very quickly, what would you do? Your answer points to the kind of problems you can solve. They give you so...