Created
February 28, 2013 16:30
-
-
Save leoallen85/5057990 to your computer and use it in GitHub Desktop.
An introduction to class methods in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HTML | |
def initialize(str) | |
@str = str | |
end | |
# instance method (note it makes use of an instance variable) | |
def render | |
puts "<div>#{@str}</div>" | |
end | |
# class method - no instance variables here | |
def self.render_div(str) | |
puts "<div>#{str}</div>" | |
end | |
# class method | |
def self.render_link(link, title) | |
puts "<a href=#{link}>#{title}</a>" | |
end | |
# alternative syntax, this does exactly the same as above | |
class << self | |
# class method | |
def render_div(str) | |
puts "<div>#{str}</div>" | |
end | |
# class method | |
def render_link(link, title) | |
puts "<a href=\"#{link}\">#{title}</a>" | |
end | |
end # note the end | |
end | |
html_render = HTML.new("first instance") | |
another_html_renderer = HTML.new("second instance") | |
# instance methods | |
html_render.render | |
another_html_renderer.render | |
# class methods | |
HTML.render_div("Class method") | |
HTML.render_link("google.com", 'Google') | |
# We see class methods used all over the place | |
# for example in ActiveRecord::Base, when we call | |
# ModelName.find or ModelName.all we are calling a class method | |
# | |
# | |
# class ActiveRecord::Base | |
# def self.find(id) | |
# # do stuff | |
# end | |
# def self.all | |
# # do stuff | |
# end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment