exclude和include
exclude:排除特定对象
include :包含特定对象
inject
[1,2,3].inject(0) {|memo, obj| memo + obj}
[1,2,3].inject(0, &:+)
map
a = ['bob', 'bill']
a.map(&:capitalize)
=> ["Bob", "Bill"]
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
.try(:name).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}"endmy_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,
}