Skip to content

Instantly share code, notes, and snippets.

View yangsu's full-sized avatar

Yang Su yangsu

  • San Francisco, CA
  • X @ys65
View GitHub Profile
@yangsu
yangsu / ruby-call-block.rb
Created January 28, 2013 03:44
Ruby Call Block
def call_block(&block) # NOTE: block is actually an instance of Proc
block.call 1, 2
end
call_block { |a,b| puts "Hello #{a} and #{b}" } # "Hello 1 and 2"
def yield_params
yield 1, 2
end
yield_params { |a,b| puts "#{a} and #{b}" } # "1 and 2"
@yangsu
yangsu / ruby-method-encapsulation.rb
Last active December 11, 2015 20:08
Ruby Method Encapsulation
class MyClass
def self.class_method # creates a class method. Always public
"class_method"
end
def method1 # default is 'public'
"method1"
end
protected # subsequent methods will be 'protected'
def method2 # will be 'protected'
"method2"
@yangsu
yangsu / ruby-alt-method-encapsulation.rb
Last active December 11, 2015 20:08
Ruby Method Encapsulation Alternative
class MyClass
# define method 1 through 4 without and encapulation directives ...
public :method1, :method4
protected :method2
private :method3
end
a = MyClass.new
@yangsu
yangsu / ruby-instance-vars.rb
Created January 28, 2013 03:47
Ruby Instance Variables
class Person
attr :age
attr_reader :age
# gets translated into:
def age
@age
end
attr_writer :age
# gets translated into:
@yangsu
yangsu / ruby-var-encapsulation.rb
Created January 28, 2013 03:48
Ruby Variable Encapsulation
class Base
def initialize()
@x = 10
end
end
d = Base.new
puts d.x # => undefined method `x' for ... (NoMethodError)
puts d.instance_variable_get :@x # => 10
@yangsu
yangsu / ruby-class-vars.rb
Created January 28, 2013 03:49
Ruby Class Variables
module T
@@foo = 'bar'
def self.set(x)
@@foo = x
end
def self.get
@@foo
end
@yangsu
yangsu / ruby-inheritance.rb
Created January 28, 2013 03:49
Ruby Inheritance
class Base
def initialize()
@x = 10
end
end
class Derived < Base
def x
@x = 20
end
@yangsu
yangsu / ruby-module.rb
Created January 28, 2013 03:50
Ruby Module
module ToFile
def filename
"object_#{self.object_id}.txt"
end
def to_f
File.open(filename, 'w') {|f| f.write(to_s)}
end
end
class Person
include ToFile
@yangsu
yangsu / ruby-comparable.rb
Created January 28, 2013 03:51
Ruby Comparable
'begin' <=> 'end' # => -1
'same' <=> 'same' # => 0
@yangsu
yangsu / ruby-sorting-example.rb
Last active December 11, 2015 20:08
Ruby Sorting Example
class SizeMatters
include Comparable
attr :str
def <=>(anOther)
str.size <=> anOther.str.size
end
def initialize(str)
@str = str
end
def inspect