Showing posts with label meta_programming. Show all posts
Showing posts with label meta_programming. Show all posts

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!"]


Meta-programming in Ruby : Part 1 : Alias


There are altogether 16 posts on this topic of meta-programming in Ruby language. Our approach encourages hands-on experimentation. The exercises here are specially designed to facilitate self-study and other independent modes of learning.

Provided we can find time amidst our busy schedule(well, who is not busy these days?), we will also discuss meta-programming in other languages such as Lisp and python.

Code 1
class A
 def fan;
     puts "fan";
 end
def feast;
     puts "feast";
 end
end
a= A.new
a.fan
a.feast
class A
 alias :flank :fan
 alias :foo :feast
 private :fan
end
begin
a.fan
rescue
 puts ">>>>>>   private method `fan' called for #",
      ">>>>>>   Accessible unless declared \"private\" as above"
end
a.feast
a.foo
a.flank
puts "\n\n"

class Z
 attr_accessor :gear
 alias :get_gear    :gear
 alias :set_gear    :gear=
end

zoe =Z.new
zoe.gear = 34
puts zoe.gear

zoe.set_gear(34)
puts zoe.get_gear 


Results 1
[root@localhost ruby_tutor]# ruby 1alias.rb
fan
feast
>>>>>>   private method `fan' called for #
>>>>>>   Accessible unless declared "private" as above
feast
feast
fan


34
34


Code 2
class String
   alias_method :original_reverse, :reverse

   def reverse
     "Trying to reverse, please wait ... "+ original_reverse
   end
end
p "happy holy days".original_reverse

p "happy holy days".reverse


Results 2
[root@localhost ruby_tutor]# ruby   2alias_method1.rb
"syad yloh yppah"
"Trying to reverse, please wait ... syad yloh yppah"


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...