tap and try
tap
%w(x y z).push('a').shift.tap {|x| p x }.upcase.next
[].tap {|i| i << "abc"} ''.tap {|i| i << do_some_thing }
try
@person.try(:name) @person.try { |p| "#{p.first_name} #{p.last_name}" }
返回调用函数的时候是否有block参数传人:block_given?
查看数组最后一项是不是Hash:extract_options!
def my_method(*args) options = args.extract_options! puts "Arguments: #{args.inspect}" puts "Options: #{options.inspect}" end my_method(1, 2) # Arguments: [1, 2] # Options: {} my_method(1, 2, :a => :b) # Arguments: [1, 2] # Options: {:a=>:b}
跳过modle更新数据库:
ActiveRecord::Base.connection.execute("update corps set followers_count = #{followers_count} and staffers_count = #{staffers_count} where id = 1")
attributes对象:
c = Corp.last
c.send(:attributes=, {is_company_page: false, alias_id: c1.id })
获取ActiveRecord::Base中的字段值:
ap Corp
class Corp < ActiveRecord::Base {
:id => :integer,
:name => :string,
}
set_primary_key :user_id 设置主键
Duck.instance_methods(false) 获取该类定义的方法
Duck.ancestors 获取该类的祖先的超类
Class.superclass => Module 查看类的直接上级父类
class Duck
def quack
"quack"
end
end
Duck = Class.new do
define_method :quack do
"quack"
end
end
产生随机数
SecureRandom.random_number(10) => n 0=<n<=10
SecureRandom.hex(10) => 'dbd9eb4e45457682eaed'