<< Previous Page
    

    
      Table of Contents
    

    
      Next Page >>
    
  
01
%q{Objects and Methods}
# All things in ruby are objects
1.is_a? Object
=> true

'this'.is_a? Object
=> true

# Create new instance of Object
Object.new
=> #<Object:0x007fe9ac8fa258>

# Define a method
def greet
'hello'
end

# Call the method
greet
=> "hello"

# Define a method on all Objects
class Object
def greet
'hello'
end
end

Object.new.greet
=> "hello"

Object.new.respond_to? :greet
=> true

# Define method on an object
cheatsheet = Object.new

def cheatsheet.title
'The Ruby Cheatsheet'
end

# Get methods accessible by object
cheatsheet.methods
=> [:title, :instance_variable_defined?, ...

# Get methods defined on object
cheatsheet.methods(false)
=> [:title]

# Get the method object
title = cheatsheet.method(:title)
=> #<Method: #<Object:0x...>.title>

# Call it
title.call
=> "The Ruby Cheatsheet"
# Objects are instances of a class
cheatsheet.class
=> Object

# Show inheritance
cheatsheet.class.ancestors
=> [Object, Kernel, BasicObject]

# Show owner
cheatsheet.method(:method).owner
=> Kernel

cheatsheet.method(:==).owner
=> BasicObject

# Define classes like this
class Book
end
=> Book

# Assign class to a constant
Book = Class.new
=> Book

# You can also declare classes like this
book = Class.new
=> #<Class:0x00007fd9e102d830>

# Objects can have instance variables
class Book
def initialize(title)
@title = title
end
end

b = Book.new("The Ruby Cheatsheet")

b.instance_variables
#=> [:@title]
b.instance_variable_set(
:@title, "The Ruby Cheatsheet v2")

b.instance_variable_get(:@title)
#=> "The Ruby Cheatsheet v2"

# Classes can have class variables
class Book
@@size = 12
end

b.class_variable_set(:@@size, 20)

b.class_variable_get(:@@size)
=> 20
01
    
      << Previous Page
    

    
      Table of Contents
    

    
      Next Page >>