Skip to content

Instantly share code, notes, and snippets.

View ngpestelos's full-sized avatar

Nestor G Pestelos Jr ngpestelos

View GitHub Profile
@ngpestelos
ngpestelos / lab_rat.rb
Last active December 24, 2015 05:19
lab rat
# see Metaprogramming Ruby, p. 108
class C
def a_method
"C#a_method"
end
def eigenclass
class << self; self; end
end
end
@ngpestelos
ngpestelos / instance_eval.rb
Created September 29, 2013 04:16
instance_eval
# see Metaprogramming Ruby, p. 108
s1, s2 = "abc", "def"
s1.instance_eval do
def swoosh!; reverse; end
end
s1.swoosh! # cba
s2.respond_to?(:swoosh!) # false
@ngpestelos
ngpestelos / eigenclass.rb
Created September 29, 2013 04:14
eigenclass
# see Metaprogramming Ruby, p. 107
obj = Object.new
eigenclass = class << obj
self
end
eigenclass.class # Class
def obj.my_singleton_method; end
eigenclass.instance_methods.grep(/my_/) # ["my_singleton_method"]
@ngpestelos
ngpestelos / class_macro.rb
Created September 29, 2013 03:54
class macro
class C; end
class << C
def my_macro(arg)
"my_macro(#{arg}) called"
end
end
class C
my_macro :x # my_macro(x) called
@ngpestelos
ngpestelos / singleton_methods_2.rb
Created September 29, 2013 03:46
singleton methods 2
# see Metaprogramming Ruby, p. 103
class MyClass
def self.my_class_method; end
end
@ngpestelos
ngpestelos / singleton_methods.rb
Created September 29, 2013 03:34
singleton methods in Ruby
# see Metaprogramming Ruby, p. 101
str = "just a regular string"
def str.title?
self.upcase == self
end
str.title? # false
str.methods.grep(/title?/) # ["title?"]
@ngpestelos
ngpestelos / class_eval.rb
Created September 22, 2013 10:59
class eval
# see Metaprogramming Ruby, p. 93
def add_method_to(a_class)
a_class.class_eval do
def m; 'Hello!'; end
end
end
add_method_to String
puts "foo".m # Hello!
@ngpestelos
ngpestelos / current_class.rb
Created September 22, 2013 10:53
current class
# see Metaprogramming Ruby, p. 92
result = class MyClass
self
end
puts result # MyClass
@ngpestelos
ngpestelos / return_proc.rb
Created September 20, 2013 13:23
returning from a Proc
# see Metaprogramming Ruby, p. 80
def another_double
p = Proc.new { return 10 }
result = p.call
return result * 2 # will not pass here
end
puts another_double
@ngpestelos
ngpestelos / return_lambda.rb
Last active December 23, 2015 10:29
returning from a lambda
# see Metaprogramming Ruby, p. 80
def double(callable_object)
callable_object.call * 2
end
l = lambda { return 10 }
puts double(l) # 20