# from C:/Users/liuzheng/Desktop/a.rb:44:in `class_eval'
# from C:/Users/liuzheng/Desktop/a.rb:44:in `
#because class << self has new scope
yes = "yes"
ok = "ok"
metaclass = (class <
define_method(yes) do
puts ok
end
end
puts String.yes => "ok"
num = 8
7.times do
print num.type, " ", num, "\n"
num *= num
end
produces: Fixnum 8
Fixnum 64
Fixnum 4096
Fixnum 16777216
Bignum 281474976710656
Bignum 79228162514264337593543950336
Bignum 6277101735386680763835789423207666416102355444464034512896
isinstance(object, classinfo) #是否为类或继承类的实例
class A(object):
... pass
... class B(A):
... pass
>>> b = B()
>>> isinstance(b,B)
59: True
>>> isinstance(b,A)
60: True
instance_of?(object, classinfo) #是否为该类
kind_of?(object, classinfo) # #是否为类或继承类的实例
>>> type("s")
20:
>>> type(u"s")
21:
irb(main):236:0> "dd".type
=> String
>>> print '%s %s' % ("hi","world")
>>> print '%(name)s %(v)s' % {"name":1 ,"v":2}
>>> a= "world"
>>> puts "hello \t #{a}"
>>> print "hi world" #换行
>>> print "hi world", #不换行
>>> puts "hi world" #换行
>>> print "hi world" #不换行
astring = """
The body of the string
is the input lines up to
one ending with the same
text that followed the '<<'
"""
aString = < The body of the string
is the input lines up to
one ending with the same
text that followed the '<<'
END_OF_STRING
",".join([1,2,3])
[1,2,3].join(",")
>>> %q {hi world} #single-quoted string
>>> %Q {hi world} #double-quoted string
>>> range(10)
>>> xrange(10)
>>> (0..9).to_a
>>> 0..9
>>> a = "Fats Waller"
>>> a =~ /a/ #这里返回匹配位置
>>> d = re.match(r"(.+)+","abc\nccc",re.DOTALL)
>>> d.groups()
42: ('abc\nccc',)
>>> re.subn(r"(hello)","\g<1> edisonlz's","hello world")
51: ("hello edisonlz's world", 1)
irb(main):020:0> "edison:lz".gsub(/(\w+):(\w+)/,'\2,\1')
=> "lz,edison"
>>> type(r"dd")
52:
irb(main):021:0> /dd/.type
=> Regexp
class ModelBase(type):
"""Metaclass of the Model."""
def __new__(cls, name, bases, dct):
return type.__new__(cls, name, bases, dct)
def __init__(cls, name, bases, attrs):
"""
intialize name base modle attribute
param:
name:string
bases:base model
attrs: attribute
"""
super(ModelBase, cls).__init__(name, bases, attrs)
cls._initialize_attributes(cls, name, bases, attrs)
cls._initialize_manager(cls)
def _initialize_attributes(self,model_class, name, bases, attrs):
"""
Initialize the attributes of the model.
param:
model_class:object
name:string
bases:base model
attrs:attribute
"""
#主要功能:添加属性列表
model_class.attributes = {}
for k, v in attrs.iteritems():
if isinstance(v,Attribute):
model_class.attributes[k] = v
v.name = v.name or k
def _initialize_manager(self,model_class):
"""
Initializes the objects manager attribute of the model.
param:
model_class:object
"""
model_class.objects = ModelSet(model_class)
pass
class Model(object):
__metaclass__ = ModelBase
class Array
def inject(n)
each { |value| n = yield(n, value) }
n
end
def sum
inject(0) { |n, value| n + value }
end
def product
inject(1) { |n, value| n * value }
end
end
[ 1, 2, 3, 4, 5 ].sum » 15
[ 1, 2, 3, 4, 5 ].product » 120
>>> _cache = {}
... def cache(sec=10):
... def wrap(f):
... def func(*args,**kwargs):
... data = _cache.get(",".join(args))
... if not data:
... data = f(*args,**kwargs)
... _cache[",".join(args)] = data
... print "no cache"
... else:
... print "in cache"
... return data
... return func
... return wrap
...
... @cache(10)
... def page(html):
... return "response %s" % html
>>> page("haha")
no cache
70: 'response haha'
>>> page("haha")
in cache
71: 'response haha'
class Object
def memory(name)
ori = "ori_#{name}"
alias_method ori,name
define_method(name) do
cache = instance_variable_get("@#{name}")
if cache
return cache
else
cache = send(ori)
instance_variable_set("@#{name}",cache)
return cache
end
end
end
end
class A
def run
puts "sleeping"
sleep 5
"a"
end
memory(:run)
end
a = A.new
puts a.run
puts a.run
def select(n)
t = []
for i in n
t.push(i) if yield(i)
end
return t
end
=> nil
irb(main):052:0> select([1,2,3]){|i| i>2}
=> [3]
module ActiveRecordExtension
def self.included(base)
base.extend(ClassMethods)
base.class_eval do
class << self
p "Aliasing find" # Used to check if alias_method isn't
called twice
alias_method :find_without_someting, :find
alias_method :find, :find_with_someting
end
end
end
module ClassMethods # :nodoc:
def find_with_something(*args)
p "0"
x = find_without_something(*args)
p "1"
return x
end
end
end
irb(main):015:0> c = "1"
irb(main):015:0> class << c
irb(main):016:1> def to_ff
irb(main):017:2> self.to_f
irb(main):018:2> end
irb(main):019:1> end
=> nil
irb(main):020:0> c.to_ff
1.0
>>> def f(x):
... return x*2
...
>>> f(3)
>>> g = lambda x: x*2
>>> g(3)
>>> g = lambda { |x| x*2 }
>>> g.call(3)
def nTimes(aThing)
return proc { |n| aThing * n }
end
p1 = nTimes(23)
p1.call(3) » 69
p1.call(4) » 92
p2 = nTimes("Hello ")
p2.call(3) » "Hello Hello Hello "
>>> import re
... def mre(dic,text):
... rc = re.compile("|".join( map( re.escape,dic.keys() ) ) )
... print rc
... def get_value(match):
... return dic.get(match.group(0))
... return rc.sub(get_value,text)
>>> dic = {"a":"A","b":"B"}
... mre(dic,"abab")
<_sre.SRE_Pattern object at 0x01A8CED0>
115: 'ABAB'
>>> def y(n):
... for i in xrange(n):
... yield i
... for g in y(10):
... print g ,
0 1 2 3 4 5 6 7 8 9
def any(n)
t = []
for i in n
return true if yield(i)
end
return false
end
=> nil
irb(main):052:0> any([0,1,0]){|i| i!=0}
=> true
:edisonlz.id
('edison','lz')
class Base():
pass
class Car():
pass
class BMW(Base,Car):
pass
The blocks used by iterators (such as loop and each) are a little different. Normally, the local variables created in these blocks are not accessible outside the block.
[ 1, 2, 3 ].each do |x|
y = x + 1
end
[ x, y ]
produces: prog.rb:4: undefined local variable or method `x'for # (NameError)
What happens when you copy a frozen object? That depends on the method you use. If you call an object's clone method, the entire object state (including whether it is frozen) is copied to the new object. On the other hand, dup typically copies only the object's contents---the new copy will not inherit the frozen status.
str1 = "hello"
str1.freeze » "hello"
str1.frozen? » true
str2 = str1.clone
str2.frozen? » true
str3 = str1.dup
str3.frozen? » false
>>> class Base(object):
... def __p(self):
... print "private"
... def _prot(self):
... print "protected"
... def p(self):
... print "public"
>>> b = Base()
>>> b.__p()
Traceback (most recent call last):
File "", line 1, in
b.__p()
AttributeError: 'Base' object has no attribute '__p'
>>> b._prot()
protected
>>> b.p()
public
>>> b._Base__p
0: >
>>> b._Base__p()
private
class Base
def aMethod
puts "Got here"
end
private :aMethod
end
class Derived1 < Base
public :aMethod
end
class Derived2 < Base
end
Use ClassName.instance_eval to define class methods.
Use ClassName.class_eval to define instance methods.
That’s right. Not a typo. Here are some examples, shamelessly stolen from his post:
1
# Defining a class method with instance_eval
2
Fixnum.instance_eval { def ten; 10; end }
3
Fixnum.ten #=> 10
4
5
# Defining an instance method with class_eval
6
Fixnum.class_eval { def number; self; end }
7
7.number #=> 7
def method_missing(method_id, *arguments, &block)
if match = DynamicFinderMatch.match(method_id)
attribute_names = match.attribute_names
super unless all_attributes_exists?(attribute_names)
if match.finder?
class DynamicFinderMatch
def self.match(method)
df_match = self.new(method)
df_match.finder ? df_match : nil
end
def initialize(method)
@finder = :first
case method.to_s
when /^find_(all_by|last_by|by)_([_a-zA-Z]\w*)$/
@finder = :last if $1 == 'last_by'
@finder = :all if $1 == 'all_by'
names = $2
when /^find_by_([_a-zA-Z]\w*)\!$/
@bang = true
names = $1
when /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/
@instantiator = $1 == 'initialize' ? :new : :create
names = $2
else
@finder = nil
end
@attribute_names = names && names.split('_and_')
end
attr_reader :finder, :attribute_names, :instantiator
def finder?
[email protected]? && @instantiator.nil?
end
def instantiator?
@finder == :first && [email protected]?
end
def bang?
@bang
end
end
class Module
define_method(:const_missing) do |name|
name.to_s
end
A =》 'A'
python sys.path
ruby $:
rails $LOAD_PATH
$: == $LOAD_PATH
require File.join(File.dirname(__FILE__), 'boot')
# All that for this:
Rails.boot!
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def preinitialize
load(preinitializer_path) if File.exist?(preinitializer_path)
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
end
# Rails::Initializer.run do |config|
# config.frameworks -= [ :action_mailer ]
# end
class Initializer
def self.run(command = :process, configuration = Configuration.new)
yield configuration if block_given?
initializer = new configuration
initializer.send(command)
initializer
end
def process
Rails.configuration = configuration
check_ruby_version
install_gem_spec_stubs
set_load_path
add_gem_load_paths
require_frameworks
set_autoload_paths
add_plugin_load_paths
load_environment
preload_frameworks
initialize_encoding
initialize_database
initialize_cache
initialize_framework_caches
initialize_logger
initialize_framework_logging
initialize_dependency_mechanism
initialize_whiny_nils
initialize_time_zone
initialize_i18n
initialize_framework_settings
initialize_framework_views
initialize_metal
add_support_load_paths
check_for_unbuilt_gems
load_gems
load_plugins
# pick up any gems that plugins depend on
add_gem_load_paths
load_gems
check_gem_dependencies
# bail out if gems are missing - note that check_gem_dependencies will have
# already called abort() unless $gems_rake_task is set
return unless gems_dependencies_loaded
load_application_initializers
# the framework is now fully initialized
after_initialize
# Setup database middleware after initializers have run
initialize_database_middleware
# Prepare dispatcher callbacks and run 'prepare' callbacks
prepare_dispatcher
# Routing must be initialized after plugins to allow the former to extend the routes
initialize_routing
# Observers are loaded after plugins in case Observers or observed models are modified by plugins.
load_observers
# Load view path cache
load_view_paths
# Load application classes
load_application_classes
# Disable dependency loading during request cycle
disable_dependency_loading
# Flag initialized
Rails.initialized = true
end
def default_load_paths
paths = []
# Add the old mock paths only if the directories exists
paths.concat(Dir["#{root_path}/test/mocks/#{environment}"]) if File.exists?("#{root_path}/test/mocks/#{environment}")
# Add the app's controller directory
paths.concat(Dir["#{root_path}/app/controllers/"])
# Followed by the standard includes.
paths.concat %w(
app
app/metal
app/models
app/controllers
app/helpers
app/services
lib
vendor
).map { |dir| "#{root_path}/#{dir}" }.select { |dir| File.directory?(dir) }
paths.concat builtin_directories
end
return to environment.rb
proceed......
class NilClass
def try(*args)
nil
end
end
=> nil
user = User.find(100)
user ? user.name : nil
user.try(:name)
class Object
def blank?
return respond_to?(:empty) ? empty? : !self
end
def present?
!blank?
end
end
=> nil
a = ""
=> ""
a.present?
=> false
a.blank?
=> true
yes = "yes"
ok = "ok"
String.class_eval do
define_method(yes) do
print ok
end
end
puts "123".yes #=> ok
#create singleton methods
#String.class_eval do
# class << self
# define_method(yes) do
# print ok
# end
# end
#end
#puts String.yes
#C:/Users/liuzheng/Desktop/a.rb:46:in `singletonclass': undefined local variable
#or method `yes' for # (NameError)
# from C:/Users/liuzheng/Desktop/a.rb:45:in `block in '
# from C:/Users/liuzheng/Desktop/a.rb:44:in `class_eval'
# from C:/Users/liuzheng/Desktop/a.rb:44:in `'
#because class << self has new scope
yes = "yes"
ok = "ok"
metaclass = (class <metaclass.class_eval do
define_method(yes) do
puts ok
end
end
puts String.yes => "ok"