Power Ruby

646 views
586 views

Published on

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
646
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
18
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Power Ruby

    1. 1. POWER RUBY Sarah Allen
    2. 2. METHOD_MISSINGWhen you send a message to a Ruby object, Ruby looksfor a method to invoke with the same name as themessage you sent.You can override method_missing anywhere along thatmethod lookup path, and tell Ruby what to do when itcan’t find a method.Developers often use this to create domain-specificlanguages (DSLs) in Ruby.
    3. 3. RUBY’S METHOD LOOKUP PATH1. The current self object’s own instance methods.2. In the list of instance methods that all objects of that class share3. In each of the included modules of that class, in reverse order of inclusion4. The superclass5. Then in the superclass’s included modules, all the way up until it reaches the class Object.6. If it still can’t find a method, the very last place it looks is in the Kernel module, included in the class Object.7. And there, if it comes up short, it calls method_missinghttp://www.thirdbit.net/articles/2007/08/01/10-things-you-should- know-about-method_missing/
    4. 4. class Thing def method_missing(m, *args, &block) puts "Theres no method called #{m} here -- please try again." puts "parameters = #{args.inspect}" endend>> t = Thing.new>> t.anything("ddd",3)Theres no method called anything here -- please try again.parameters = ["ddd", 3]=> nil
    5. 5. VARIABLE ARGUMENTSdef test(*params) params.each_with_index do |arg, i| puts "#{i} #{arg}" endend
    6. 6. VARIABLE ARGUMENTSdef test(a, b, *params) params.each_with_index do |arg, i| puts "#{i} #{arg}" endend
    7. 7. HASH ARGUMENTSdef test(options) a = options[:a] b = options[:b]endtest(:a => 1, :b =>2)test({:a => 1, :b =>2})test :a => 1, :b =>2test {:a => 1, :b =>2}
    8. 8. HASH ARGUMENTSdef test(name, options) a = options[:a] b = options[:b]endtest("foo", :a => 1, :b =>2)test("foo", {:a => 1, :b =>2})test "foo", :a => 1, :b =>2test "foo", {:a => 1, :b =>2}

    ×