From d35cf8e8021203bcdb5b0f3d8a6e290b1c7e54cd Mon Sep 17 00:00:00 2001 From: Karthikeyan A K Date: Tue, 29 Oct 2013 21:55:44 +0530 Subject: [PATCH] metaprogramming started --- aray_1.rb => array_1.rb | 0 aray_2.rb => array_2.rb | 0 define_method.rb | 10 ++++++++++ function_many_arguments.rb | 3 ++- inheritance.rb | 2 +- method_missing.rb | 15 +++++++++++++++ method_missing_in_action.rb | 18 ++++++++++++++++++ send.rb | 12 ++++++++++++ 8 files changed, 58 insertions(+), 2 deletions(-) rename aray_1.rb => array_1.rb (100%) rename aray_2.rb => array_2.rb (100%) create mode 100644 define_method.rb create mode 100644 method_missing.rb create mode 100644 method_missing_in_action.rb create mode 100644 send.rb diff --git a/aray_1.rb b/array_1.rb similarity index 100% rename from aray_1.rb rename to array_1.rb diff --git a/aray_2.rb b/array_2.rb similarity index 100% rename from aray_2.rb rename to array_2.rb diff --git a/define_method.rb b/define_method.rb new file mode 100644 index 0000000..bee7bae --- /dev/null +++ b/define_method.rb @@ -0,0 +1,10 @@ +# define_method.rb + +class Square + define_method :area do |side| + side * side + end +end + +s = Square.new +puts s.area 5 diff --git a/function_many_arguments.rb b/function_many_arguments.rb index a01cdc4..869ca95 100644 --- a/function_many_arguments.rb +++ b/function_many_arguments.rb @@ -5,4 +5,5 @@ def print_line char = '_' length = 20 end print_line -print_line 40 +print_line '*' +print_line '&', 40 diff --git a/inheritance.rb b/inheritance.rb index f69e6c2..4e488be 100644 --- a/inheritance.rb +++ b/inheritance.rb @@ -28,7 +28,7 @@ def side_length end def side_length=(length) - @width = @height = length + @width = @length = length end end diff --git a/method_missing.rb b/method_missing.rb new file mode 100644 index 0000000..455a0c1 --- /dev/null +++ b/method_missing.rb @@ -0,0 +1,15 @@ +# method_missing.rb + +class Something + def method_missing method, *args, &block + puts "You called: #{method}" + p args + block.call 7 + end +end + +s = Something.new +s.call_method "boo", 5 do |x| + x.times{ puts "in block" } +end + diff --git a/method_missing_in_action.rb b/method_missing_in_action.rb new file mode 100644 index 0000000..d029aac --- /dev/null +++ b/method_missing_in_action.rb @@ -0,0 +1,18 @@ +# method_missing_in_action.rb + +class Person + attr_accessor :name, :age + + def initialize name, age + @name, @age = name, age + end + + def method_missing method_name + method_name.to_s.match(/get_(\w+)/) + eval("self.#{$1}") + end +end + +person = Person.new "Zigor", "67893" +puts "#{person.get_name} is #{person.get_age} years old" + diff --git a/send.rb b/send.rb new file mode 100644 index 0000000..8550429 --- /dev/null +++ b/send.rb @@ -0,0 +1,12 @@ +class Person + attr_accessor :name + + def speak + "Hello I am #{@name}" + end +end + + +p = Person.new +p.name = "Karthik" +puts p.send(:speak)