Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created September 6, 2012 00:35
Show Gist options
  • Select an option

  • Save steveklabnik/3648804 to your computer and use it in GitHub Desktop.

Select an option

Save steveklabnik/3648804 to your computer and use it in GitHub Desktop.
rubylearning
Struct.new("Point", :x, :y) #=> Struct::Point
origin = Struct::Point.new(0,0) #=> #<struct Struct::Point x=0, y=0>
class Point < Struct.new(:x, :y)
end
origin = Point.new(0,0)
1.9.3p194 :001 > Struct.new(:x,:y) => #<Class:0x007f8fc38da2e8>
Point = Struct.new(:x, :y)
origin = Point.new(0,0)
Point = Struct.new(:x, :y) do
def translate(x,y)
self.x += x
self.y += y
end
end
origin = Point.new(0,0)
origin.translate(1,2)
puts origin #=> <struct Point x=1, y=2>
require 'ostruct'
origin = OpenStruct.new
origin.x = 0
origin.y = 0
origin = OpenStruct.new(:x => 0, :y => 0)
require 'ostruct'
def set_options
opts = OpenStruct.new
yield opts
opts
end
options = set_options do |o|
o.set_foo = true
o.load_path = "whatever:something"
end
options #=> #<OpenStruct set_foo=true, load_path="whatever:something">
class Person
attr_accessor :name, :day, :month, :year
def initialize(opts = {})
@name = opts[:name]
@day = opts[:day]
@month = opts[:month]
@year = opts[:year]
end
def birthday
"#@day/#@month/#@year"
end
end
$:.unshift("lib")
require 'person'
describe Person do
it "compares birthdays" do
joe = Person.new(:name => "Joe", :day => 5, :month => 6, :year => 1986)
jon = Person.new(:name => "Jon", :day => 7, :month => 6, :year => 1986)
joe.birthday.should == jon.birthday
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment