The Well-Grounded
                                  Nuby
                               Advice for Ruby newcomers*

      ...
About me
                     •      Senior Developer at Cyrus Innovation, Inc.
                     •      Rubyist-at-lar...
Goals for today
                     • Learn some major common points of
                            confusion, and how to...
How we'll proceed
                     • Seven major points, with code demos
                      • chosen because they a...
I.
                         Every expression
                       evaluates to an object

                              ...
•    Everything is not an object
                            •   if statements aren't
                            •   argu...
irb is your friend
                                        >> if 3 > 5
             A failed if statement
                ...
II.
                            It's all about sending
                            messages to objects

                  ...
Messages everywhere...
                     • Post-dot messages are... messages
                      • as in "abc".upcase...
Operators are (mostly)
                             messages (methods)
                                This...   ...is rea...
Roll your own + logic!
                            class Person
                              attr_accessor :name
        ...
Even case statements send
                               messages to objects!
                   This...            ...is ...
Roll your own ===!
                                                               Strictly speaking, you
                 ...
III.
                     Objects resolve
                  messages into methods

                                    Cop...
The intelligence of
                                      objects
                     •      Objects do not "have" method...
from The Well-Grounded Rubyist, © 2009 Manning Publications

                                                             ...
class Person
                              attr_accessor :name
                            end

                          ...
class Person
                              attr_accessor :name
                            end

                          ...
class Person
                              attr_accessor :name
                            end

                          ...
class Person
                              attr_accessor :name
                            end

                          ...
IV.
                            Classes and modules
                                 are objects

                        ...
"The answer to 75% of all questions about Ruby is: Because classes are objects!"

                                        ...
Classes and modules as
                          objects
                     •      You can send them messages

         ...
Seen in the wild...

                            def do_something(class_string)
                              THINGS.each ...
Don't work so hard!

                             def do_something(klass)
                               THINGS.each do |t...
Classes are objects
                                         class Person
                                         end
   ...
V.
                    There's always a self


                                      Copyright © 2010, Ruby Power and Ligh...
self-centeredness
                    •       self is the default receiver of messages
                    •       self ow...
self
                            class Person
                              puts "self in the class definition body: #{sel...
self
                            str = "I am a string!"
                            puts "self is: #{self}"
              ...
self
                            my_class = Class.new
                            my_class.class_eval do
                 ...
VI.
                              Variables contain
                            references to objects

                   ...
str = "Hi"
                            str2 = str
                            str2 << " there!"
                          ...
array = [1,2,3]
                            array2 = array
                            array2[3] = 4
                     ...
one = "one"
                            array = [one, "Two", "Three"]
                            one.capitalize!
        ...
str = "Hi"
                                          str2 = str
                       += creates a new   str2 += " there"...
def add_bang(string)
                              string << "!"
                            end

                        ...
VII.
                  true and false are objects;
                    true and false are states



                      ...
Truth and falsehood
                     •      Every object has a boolean value
                     •      The objects f...
The truth test
                        For any object obj, think of:

                        if obj
                     ...
Summary
                     I. Every expression evaluates to an object
                     II. It's all about sending me...
Questions so far?



                                            Copyright © 2010, Ruby Power and Light, LLC


Friday, Sep...
What do these evaluate to,
                             what do they output,
                                   and why?

...
10 if false

                            10 if true

                            puts 10 if true

                        ...
class Talker
                              @x = 1
                              def talk
                                p...
class Talker
                              def talk
                               @x = 1
                               p...
class C
                              def talk
                                puts "Hi!"
                              en...
class C
                              "Hi!"
                            end




                                      Copy...
class C
                              self
                            end




                                      Copyr...
obj = Object.new
                            class << obj
                              self
                            e...
class Person
                              attr_accessor :name
                            end

                          ...
class Person
                              attr_accessor :name
                            end

                          ...
class Person
                              attr_accessor :name
                            end

                          ...
That's all!

                            Enjoy your Ruby literacy!



                            David A. Black
         ...
Upcoming SlideShare
Loading in …5
×

The Well-Grounded Nuby

3,528 views

Published on

Advice on Ruby things to concentrate on as you're learning the language (or helping others learn it), to help you avoid misunderstandings later on.

Published in: Technology
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,528
On SlideShare
0
From Embeds
0
Number of Embeds
17
Actions
Shares
0
Downloads
58
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide

The Well-Grounded Nuby

  1. 1. The Well-Grounded Nuby Advice for Ruby newcomers* David A. Black Senior Developer Cyrus Innovation, Inc. * and their mentors! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  2. 2. About me • Senior Developer at Cyrus Innovation, Inc. • Rubyist-at-large since 2000 (Pickaxe baby) • Owner/director of Ruby Power and Light, LLC • Author of Ruby for Rails (Manning, 2006) and The Well- Grounded Rubyist (Manning, 2009) • Director of Ruby Central, Inc. (RubyConf, RubyForge, etc.) • Twitter: @david_a_black, @compleatrubyist • Ruby learning and history: http://www.ruby-versions.net Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  3. 3. Goals for today • Learn some major common points of confusion, and how to navigate them • Improve your ability to understand Ruby code • Give yourself some tools for reasoning through code as you write it Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  4. 4. How we'll proceed • Seven major points, with code demos • chosen because they are common stumbling blocks, even among experienced Ruby programmers • Examples of how the seven points can help you understand Ruby • Questions (throughout) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  5. 5. I. Every expression evaluates to an object Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  6. 6. • Everything is not an object • if statements aren't • argument lists aren't • keywords aren't • But everything evaluates to an object • including if statements, method definitions, class definitions Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  7. 7. irb is your friend >> if 3 > 5 A failed if statement >> "Not reached!" returns nil >> end => nil >> puts "Hello!" puts returns nil Hello! => nil Empty class definition >> class C evaluates to nil >> end => nil Class definition >> class C >> "Some value in a class definition" evaluates to the >> end last expression inside => "Some value in a class definition" it Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  8. 8. II. It's all about sending messages to objects Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  9. 9. Messages everywhere... • Post-dot messages are... messages • as in "abc".upcase • Infix and unary operators are (mostly) messages • Square brackets are a message • case statements send messages Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  10. 10. Operators are (mostly) messages (methods) This... ...is really this! 3+2 3.+(2) 5*3 5.*(3) a[2] a.[](2) (Except you can't actually call the +x x.+@ +@ method this way.) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  11. 11. Roll your own + logic! class Person attr_accessor :name class Couple def initialize(one, two) @pair = [one, two] end def to_s @pair[0].name + " and " + @pair[1].name end end def +(other) Adding two people is defined Couple.new(self, other) end as returning a Person::Couple end object with those two people. john = Person.new john.name = "John" marcia = Person.new marcia.name = "Marcia" couple = john + marcia puts couple John and Marcia Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  12. 12. Even case statements send messages to objects! This... ...is really this... ...which is really this!... case some_string if "abc" === some_string if "abc".===(some_string) when "abc" # ... # ... # ... elsif /def/ === some_string elsif /def/.===(some_string) when /def/ # ... # ... # ... end end end Case statements use the === method, aka the case equality operator, to determine a match Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  13. 13. Roll your own ===! Strictly speaking, you class Person attr_accessor :name, :ssn could just define == def ===(other) here, since === is the self.ssn == other.ssn same as == by default. end end But defining === itself means that you can david = Person.new separate "plain" equality david.ssn = "123-45-6789" from case equality if you joe = Person.new wish to. joe.ssn = "987-65-4321" mystery = david case mystery when joe # i.e., if joe === mystery puts "It's Joe!" when david # i.e., if david === mystery puts "It's David!" end It's David! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  14. 14. III. Objects resolve messages into methods Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  15. 15. The intelligence of objects • Objects do not "have" methods • they have the intelligence to find methods when required to do so • Methods are stored in classes and modules • Every object has a lookup-path consisting of classes and modules • singleton class • modules mixed into singleton class • class • modules mixed into class • superclass, etc., all the way up Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  16. 16. from The Well-Grounded Rubyist, © 2009 Manning Publications Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  17. 17. class Person attr_accessor :name end david = Person.new david.name = "David" Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  18. 18. class Person attr_accessor :name end david = Person.new david.name = "David" module Vocal def talk "Hi, my name is #{name}." end end class Person include Vocal end puts david.talk Hi, my name is David. Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  19. 19. class Person attr_accessor :name end david = Person.new david.name = "David" module Vocal def talk "Hi, my name is #{name}." end end class Person include Vocal end puts david.talk module Loud def talk super.upcase.chomp('.') + "!!!" end end class Person include Loud end puts david.talk HI, MY NAME IS DAVID!!! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  20. 20. class Person attr_accessor :name end david = Person.new david.name = "David" module Vocal def talk "Hi, my name is #{name}." end end class Person include Vocal end puts david.talk module Loud def talk super.upcase.chomp('.') + "!!!" end end class Person include Loud end puts david.talk module Quiet def talk "(((" + super.delete('!').downcase + ".)))" end end david.extend(Quiet) (((hi, my name is david.))) puts david.talk Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  21. 21. IV. Classes and modules are objects Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  22. 22. "The answer to 75% of all questions about Ruby is: Because classes are objects!" -- Me Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  23. 23. Classes and modules as objects • You can send them messages • They can be put in arrays, etc. • They can be assigned to local variables • They have state (instance variables), just like other objects • They have some special behaviors (nesting, instantiation, inclusion in lookup path, etc.) • but in many respects, they are just objects! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  24. 24. Seen in the wild... def do_something(class_string) THINGS.each do |thing| str = "#{Object.const_get(class_string)}" str << ".#{thing}_method" eval str end end do_something(an_object.class.name) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  25. 25. Don't work so hard! def do_something(klass) THINGS.each do |thing| klass.send("#{thing}_method") end end do_something(an_object.class) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  26. 26. Classes are objects class Person end You can put a class in a my_class = Person local variable! david = my_class.new You can't use it with the # class my_class # ERROR! class keyword. However... my_class.class_eval do def speak puts "Hi!" end end david.speak # Hi! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  27. 27. V. There's always a self Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  28. 28. self-centeredness • self is the default receiver of messages • self owns instance variables • and, by definition, any instance variable you see belongs to self • The value of self changes: • in class definition (becomes the class) • in method definition (to object that will call method) • in instance_eval (becomes the receiver) • in class_eval (becomes the class/module) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  29. 29. self class Person puts "self in the class definition body: #{self}" def speak puts "Hi! self in the instance method: #{self}" end end puts "self at the top level: #{self}" david = Person.new david.speak self in the class definition body: Person self at the top level: main Hi! self in the instance method: #<Person:0x1281bc> Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  30. 30. self str = "I am a string!" puts "self is: #{self}" str.instance_eval do puts "self is now: #{self}" puts upcase end self is: main self is now: I am a string! I AM A STRING! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  31. 31. self my_class = Class.new my_class.class_eval do puts "self in class_eval is: #{self}" end self in class_eval is: #<Class:0x12857c> Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  32. 32. VI. Variables contain references to objects Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  33. 33. str = "Hi" str2 = str str2 << " there!" puts str Hi there! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  34. 34. array = [1,2,3] array2 = array array2[3] = 4 p array [1, 2, 3, 4] Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  35. 35. one = "one" array = [one, "Two", "Three"] one.capitalize! puts one p array One ["One", "Two", "Three"] Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  36. 36. str = "Hi" str2 = str += creates a new str2 += " there" string object! puts str Hi Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  37. 37. def add_bang(string) string << "!" end str = "Hi" add_bang(str) puts str Hi! Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  38. 38. VII. true and false are objects; true and false are states Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  39. 39. Truth and falsehood • Every object has a boolean value • The objects false and nil have a boolean value of false. • Every other object has a boolean value of true. • true is true • 0 is true • "" is true • [] is true Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  40. 40. The truth test For any object obj, think of: if obj puts "obj has a boolean value of true" end And remember... every expression evaluates to an object, including class definitions! if class A end puts "True!" end # No output(because the class definition evaluates to nil) if class A 0 end puts "True!" end # Output: True!(because the class definition evaluates to 0, # which has a boolean value of true) Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  41. 41. Summary I. Every expression evaluates to an object II. It's all about sending messages to objects III. Objects resolve messages into methods IV. Classes and modules are objects V. There's always a self VI. Variables contain references to objects VII. true and false are objects; true and false are states Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  42. 42. Questions so far? Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  43. 43. What do these evaluate to, what do they output, and why? Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  44. 44. 10 if false 10 if true puts 10 if true if 10 > 3 puts "True!" else puts "Not true!" end if 10 > 3 "True!" end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  45. 45. class Talker @x = 1 def talk puts "x is #{@x}" end end t = Talker.new t.talk Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  46. 46. class Talker def talk @x = 1 puts "x is #{@x}" end end t = Talker.new t.talk Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  47. 47. class C def talk puts "Hi!" end end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  48. 48. class C "Hi!" end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  49. 49. class C self end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  50. 50. obj = Object.new class << obj self end Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  51. 51. class Person attr_accessor :name end d = Person.new d.name = "David" puts d.name d.instance_eval { puts name } Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  52. 52. class Person attr_accessor :name end d = Person.new d.name = "David" puts d.name d.instance_eval { puts @name } Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  53. 53. class Person attr_accessor :name end d = Person.new d.name = "David" @name = "Matz" puts d.name d.instance_eval { puts @name } Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010
  54. 54. That's all! Enjoy your Ruby literacy! David A. Black Senior Developer Cyrus Innovation, Inc. dblack@rubypal.com Copyright © 2010, Ruby Power and Light, LLC Friday, September 3, 2010

×