Permalink
Browse files

Explanation for method name shorthand.

  • Loading branch information...
jaymcgavren committed Feb 27, 2011
1 parent 3ac70cb commit 21033754019ad8501f91c0e49699d4a23d94b3e4
Showing with 38 additions and 9 deletions.
  1. +38 −9 ruby_tweets/8_shorthand.rb
View
@@ -1,11 +1,40 @@
-def method_missing *m;s=m.shift;method(methods.find{|n|n=~/^#{s}/})[*m];end
-# class Object;def method_missing(*m);shorthand = m.shift, me, methods;end;end
-# class Object;def method_missing(*m);p m.shift, methods, *m;end;end
-# class Object;def method_missing(*m);s=m.shift;p methods.find{|n|n=~/^#{s}/}, *m;end;end
-# def method_missing(*m);s=m.shift;p methods.find{|n|n=~/^#{s}/},*m;end
-# def m s;method methods.find{|n|n=~/^#{s}/};end
+# ruby -e "def method_missing(*m);s=m.shift;method(methods.find{|n|n=~/^#{s}/})[*m];end;p 'XXzAzTTzq'.rev.sp(/z/).map{|l|l.sq.suc}.jo.sw"
-# puts 'a'.dafdsadfs
-# puts 'hello'.inc('foo')
+#Re-define Object.method_missing().
+def method_missing(*m)
-"TSUjzREHTONazYBUrzREKCAh".rev.sp(/z/).rev.map{|o|o.sw}.jo(' ')
+ #The symbol for the failed method call.
+ shorthand = m.shift
+
+ #Arguments, if any, follow the method name.
+ arguments = m
+
+ #methods() gives all defined method names for the current object.
+ method_names = methods
+
+ #Find the first method where the shorthand matches the start of its name.
+ #You'll have to supply enough of the method name to ensure it's unique.
+ #Otherwise, you could call a different method with a similar name.
+ full_method_name = method_names.find do |name|
+ name =~ /^#{shorthand}/
+ end
+
+ #method() gives the actual method reference, given the name.
+ method_reference = method(full_method_name)
+
+ #Splatting the argument array ensures that if it's empty,
+ #the methods will be called with no arguments.
+ method_reference.call(*arguments)
+
+end
+
+p 'XXzAzTTzq'.
+ rev. #String#reverse()
+ sp(/z/). #String#split()
+ map{|l| #Array#map()
+ l. #['q', 'TT', 'A', XX], in order
+ sq. #String#squeeze()
+ suc #String#succ()
+ }.
+ jo. #Array#join('')
+ sw #String#swapcase()

0 comments on commit 2103375

Please sign in to comment.