Skip to content

Instantly share code, notes, and snippets.

#The clone method also copies over the singleton methods of the receiver
porsche = Object.new
def porsche.number_of_wheels
4
end
puts "porsche has #{porsche.number_of_wheels}"
porsche_clone = porsche.clone
puts "porsche's clone has #{porsche_clone.number_of_wheels}"
#Struct.new returns a class object that has attributes that you pass in
Car = Struct.new(:wheels, :rpm) #Car is a Class object that has attributes *wheels* & *rpm* now
porsche = Car.new(4,1600)
#Since Struct.new is basically an expression returning a Class object - even the following would work
class Car < Struct.new(:wheels,:rpm)
end
#Keeping track of number instances of a class without actually creating getter and setter methods
class Foo
@count = 0
#Create a singleton class for self - which is currently the Foo class object
class << self
attr_accessor :count
end
def initialize
#A typical ActiveRecord Model would need to extends ActiveRecord::Base, like so:
class Person < ActiveRecord::Base
end
#And now we have access to class & instance level methods like find & save
p = Person.find 1
p.save
#A non-inheritance based re-write of the above code - i.e. one that does not require
#When a proc calls a return - it returns from the context
def method
puts "at top of method"
p = Proc.new { return }
p.call
puts "at bottom of method"
end
puts "before call"
#Re-writing a method inside itself can be done in ruby
def meth1
def meth1
end
puts "in old method"
end
meth1 #This prints "in old method"
meth1 #This does not
#We can force the execution order of methods
class Foo
def start
def stop
end
end
end
f = Foo.new
@santosh79
santosh79 / my_attr_accessor.rb
Created November 16, 2009 22:33
This snippet shows how to create accessors in ruby
module Accessor
def my_attr_accessor(*names)
names.each do |name|
ivar_name = "@#{name}"
define_method(name) do
instance_variable_get(ivar_name)
end
define_method("#{name}=") do |val|
@santosh79
santosh79 / creating_an_accessor_with_class_eval.rb
Created November 17, 2009 05:07
Accessors with class_eval
module Accessor
def my_attr_accessor(*names)
names.each do |name|
class_eval %{
def #{name}
@#{name}
end
def #{name}=(val)
@#{name} = val
@santosh79
santosh79 / automating_includes.rb
Created November 17, 2009 05:29
automating includes with class_eval
module Hello
def say_hello
puts "hello"
end
end
[String, Array, Hash].each do |cls|
cls.class_eval { include Hello }
end