Ruby : Various ways to define class methods

# 1
class Rubyist
  def self.who
    "Geek"
  end
end
p Rubyist.who # => "Geek"
# 2
class Rubyist
  class << self
    def who
      "Geek"
    end
  end
end

# 3
class Rubyist
end
def Rubyist.who
  "Geek"
end

#4
class Rubyist
end
Rubyist.instance_eval do
  def who
    "Geek"
  end
end
puts Rubyist.who # => Geek

Sources:
http://www.intridea.com/blog/2012/2/13/using-anonymous-classes-and-modules-in-ruby

http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_1.html

http://blog.jayfields.com/2008/02/ruby-creating-anonymous-classes.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s